PHP Non Recursive Function Through Directories

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.

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

1 comment

  1. zaf

    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!

Comments are closed.