Looping a file structure

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Looping a file structure

Post 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 :)
Post Reply