Optimizing a file navigator
<p>I've come up with a basic file navigator that accepts user input to jump to different directories. The only problem I have with it is that I'm basically looping over the data three times:</p>

<ol>
<li>Get a valid list of all directories for comparison against user input</li>
<li>Build a "sorted" list of directories and files</li>
<li>Output final list</li>
</ol>

<p>Any tips on optimizing or improving this code?</p>

<pre><code>define('ROOT', '/path/to/somewhere');

// get a list of valid paths
$valid = array();
$dir = new RecursiveDirectoryIterator(ROOT);
$dir-&gt;setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$iter = new ParentIterator($dir);
foreach(new RecursiveIteratorIterator($iter, RecursiveIteratorIterator::SELF_FIRST) as $file) {
    $path = str_replace(ROOT, '', $file-&gt;getPathname());
    $valid[] = $path;
}

// user input
$subpath = isset($_GET['path']) &amp;&amp; in_array($_GET['path'], $valid) ? $_GET['path'] : NULL;

$cwd = isset($subpath) ? ROOT.$subpath : ROOT;

// build and sort directory tree
$files = array();
foreach(new DirectoryIterator($cwd) as $file) {
    if($file-&gt;isDot()) {
        continue;
    }

    if($file-&gt;isDir()) {
        $path = str_replace(ROOT, '', $file-&gt;getPathname());
        $count = iterator_count(new RecursiveDirectoryIterator($file-&gt;getRealPath(), FilesystemIterator::SKIP_DOTS));
        $files[$path]['name'] = $file-&gt;getFilename();
        $files[$path]['count'] = $count;
    } else {
        $files[] = $file-&gt;getFilename();
    }
    asort($files);
}

// output directory tree
if(!empty($files)) {
    foreach($files as $key=&gt;$value) {
        if(is_array($value)) {
            echo "&lt;a href=\"?path=$key\"&gt;{$value['name']} ({$value['count']})&lt;/a&gt;&lt;br /&gt;";
        } else {
            echo "$value&lt;br /&gt;";
        }
    }
}
</code></pre>
