I needed a recursive function to go through directories and subdirectories, so I headed to PHP.net's readdir() page, knowing that I would find one in user comments. Or did I need a recursive function ? Hell no. I've found the nifty neat following function, which does not recursively calls itself. And what's so cool about it, you may ask ? Speed.
<?php
function list_directory($dir) {
$file_list = '';
$stack[] = $dir;
while ($stack) {
$current_dir = array_pop($stack);
if ($dh = opendir($current_dir)) {
while (($file = readdir($dh)) !== false) {
if ($file !== '.' AND $file !== '..') {
$current_file = "{$current_dir}/{$file}";
if (is_file($current_file)) {
$file_list[] = "{$current_dir}/{$file}";
} elseif (is_dir($current_file)) {
$stack[] = $current_file;
}
}
}
}
}
return $file_list;
}
?>The function returns an array of files from directory passed as argument and subdirectories. The user who submitted this function added a few benchmarks against an average recursive function, to find out that this one is about 50% quicker.
Just as anybody I guess, I've been using various recursive functions for years now, and I just had never thought about why or how to do it differently. Damn. So many CPU cycles wasted for nothing :)
Thank you for the snippet of code. At this time of night I really didn't want to write a non recursive version. You really should post it on php.net since thats where most people look and you can only find recursive versions. Of course, I'm a special case with to many directories/files to fit in memory ;)
Cheers!