directories into an array

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
Extremest
Forum Commoner
Posts: 84
Joined: Mon Aug 29, 2005 12:39 pm

directories into an array

Post by Extremest »

I am trying to figure out how I can have php look at a certain dir and then make an array of every filename in that directory then go into the subfolders getting those names with dir also. That way afterwards it could then parse every file in all the directories.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

a lot of people write recursive loops to generate such things using glob() or opendir()/readdir(). I use a different approach, because I have a general hate for recursive functions (old stack space issue). My approach uses two loops, and two arrays. The first array is for directories, the second is for files. The outer loop iterates over the directory list, while the inner loops over the results from using glob() on the current directory, tossing directories and files into their respective arrays. Rough example:

Code: Select all

$directories = array($directory);
$files = array();

for($dir = 0; $dir < count($directories); $dir++) {
  $data = glob($directories[$dir] . DIRECTORY_SEPARATOR . '*');
  foreach($data as $key => $file) {
    if(is_file($file)) {
      $files[] = $file;
    } elseif(is_dir($file)) {
      $directories[] = $file;
    }
  }
  if(!$recursion) {
    break;
  }
}
There's a flag at the end there that allows you to switch recursive searching on and off..
Extremest
Forum Commoner
Posts: 84
Joined: Mon Aug 29, 2005 12:39 pm

Post by Extremest »

ok I am still learning here. LOL... How do I implement that for the start directory.
Extremest
Forum Commoner
Posts: 84
Joined: Mon Aug 29, 2005 12:39 pm

Post by Extremest »

ok figured that out. It is not listing any files. Only the directory name that is in the main directory.
Extremest
Forum Commoner
Posts: 84
Joined: Mon Aug 29, 2005 12:39 pm

Post by Extremest »

ok removing the recursion fixed it. Is there a way I can have it remove the dir names that have no file name behind them? That way I just have an array of the dir and filename for the ones that have files. That way I can have my other script go through the array and open the files.
Extremest
Forum Commoner
Posts: 84
Joined: Mon Aug 29, 2005 12:39 pm

Post by Extremest »

ok I am an idiot. I was cehcking the wrong array. It works perfect now. Should be what I need think you very much.
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Post by dude81 »

gr8 today I learnt one new fucntion glob().
Thanks feyd
Post Reply