# Recursive directory listing

I'm trying to optimize performance for recursive directory listing with some exceptions:

function listdir($basedir) { global$root, $ignore_dirs,$ignore_files, $filetypes,$ignore_starts_with;
if ($handle = @opendir($basedir)) {
while (false !== ($fn = readdir($handle))) {
if ($fn != '.' &&$fn != '..') {

$s = true; foreach ($ignore_starts_with as $pre) if (strpos($fn, $pre) === 0)$s = false;

$dir =$basedir."/".$fn; if ($s && is_dir($dir) && !in_array($fn, $ignore_dirs)) { listdir($dir);
} else {

if ($s && !in_array($fn,$ignore_files) && preg_match("/[^.\/].+\.($filetypes)$/",$dir,$fname)) printlink($fname[0]);
}
}
}
closedir($handle); } }  • Optimize how? Where is the bottleneck? What have your profiling results shown? – Ed S. Jul 29 '11 at 17:51 • im not shire about foreach construction, and many if's – 350D Jul 29 '11 at 18:27 • Well, I would prove that is actually a bottleneck before potentially wasting time optimizing them out (if that's even possible). For example, if 98% of your time is spent doing I/O then removing an if statement or a loop is pointless. That said, your $s variable will only hold the last assignment, so you may as well just break out of it the first time that condition is met. – Ed S. Jul 29 '11 at 18:39