In: ,
On: 2005 / 12 / 22 Viewed: 59967 times
Shorter URL for this post:

I needed a recursive function to go through directories and subdirectories, so I headed to'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.

  1. <?php
  2. function list_directory($dir) {
  3.    $file_list = '';
  4.    $stack&#91;&#93; = $dir;
  5.   while ($stack) {
  6.       $current_dir = array_pop($stack);
  7.       if ($dh = opendir($current_dir)) {
  8.          while (($file = readdir($dh)) !== false) {
  9.             if ($file !== '.' AND $file !== '..') {
  10.                $current_file = "{$current_dir}/{$file}";
  11.                if (is_file($current_file)) {
  12.                   $file_list&#91;&#93; = "{$current_dir}/{$file}";
  13.               } elseif (is_dir($current_file)) {
  14.                   $stack&#91;&#93; = $current_file;
  15.               }
  16.             }
  17.          }
  18.       }
  19.    }
  20.    return $file_list;
  21. }
  22. ?>

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 :)

Shorter URL

Want to share or tweet this post? Please use this short URL:


This entry "PHP Non Recursive Function Through Directories" was posted on 22/12/2005 at 12:07 am and is tagged with ,
Watch this discussion : Comments RSS 2.0.

One Reply

  1. zaf says:

    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 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 ;)


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?