Page 1 of 1

Looping a file structure

Posted: Sun May 04, 2008 3:27 pm
by aliasxneo

Code: Select all

private static function getFiles($path, $match){
       $dirs = glob($path . "*");
       $files = glob($path . "*" . $match);
       
       foreach($files as $file)
       {
          if(is_file($file))
          {
             $name = str_replace(".php", "", basename($file));
             self::$files[$name] = $file;
          }
       }
       
       foreach($dirs as $dir)
       {
          if(is_dir($dir))
          {
             $dir = basename($dir) . "/";
             self::getFiles($path . $dir, $match);
          }
       }
    }
That's the function I'm currently using to loop through a file structure. Essentially all I am doing is looping through the given path, parsing out all php files and adding them to $files so that the key is the file name (without the .php) and the value is the path to the file. Then if it encounters any directories it iterates back through the function.

While it does work, it seems a bit too bulky and I'm not sure why. Not to mention I've heard glob is a bit slower and should not be used when looping through an entire file structure. So can anyone give some tips on how to fix this up or some examples that don't use glob? Thanks :)