note 47362 added to function.readdir

From: Date: Sat, 13 Nov 2004 10:20:58 +0000
Subject: note 47362 added to function.readdir
Groups: php.notes 
Request: Send a blank email to php-notes+get-80460@lists.php.net to get a copy of this message
Everyone seems to be using recursion for trawling through subdirectories. Here's a function that does not use recursion. <?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; } ?> I also did a rudimentary benchmark against Rick's function (no reason in particular why I chose Rick's, it was just the latest) and the result is that using recursion results in about 50% longer execution time. Details of benchmark: Directory contains 64 subdirectories and about 117,000 files. Each function was executed 100 times in a for-loop and the average time per iteration was calculated. The result is 3.77 seconds for the non-recursive function and 5.65 seconds for the recursive function. ---- Manual Page -- http://www.php.net/manual/en/function.readdir.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+47362 Delete -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47362&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+47362&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#80460) next »