directories into an array
Moderator: General Moderators
directories into an array
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.
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
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:There's a flag at the end there that allows you to switch recursive searching on and off..
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;
}
}