Skip to main content

Posts

Showing posts from July, 2012

PHP Recursive Directory Traversal

It sounds like a simple enough task: Generate an array that mirrors a directory structure. Directories may have subdirectories (arbitrary nesting), and entries should be alphabetized with directories grouped first. The image below shows what the array should look like given a sample directory. While not terribly difficult, there are a few snags that can trip you up if you're not careful. For me, the first snag was trying to do it “the right way.” The RecursiveDirectoryIterator “provides an interface for iterating recursively over filesystem directories” ( php.net ), so this was my first approach. I hacked together this code after a short while: <?php function getDirectoryList($dir) { $dirList = []; $dirIter = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $iterIter = new RecursiveIteratorIterator($dirIter); foreach ($iterIter as $entry) { $path = substr($entry->getPath(), strlen($dir) - 1); $keys = "