Tag Archives: Recursion

PHP: Pathable RecursiveIteratorIterator

Needed to recursively loop through a multi-dimensional array and print out each leaf-node with its full “path”.

For this I used an RecursiveArrayIterator for the array and a RecursiveIteratorIterator for the recursion. Thought I was home free because I had used a method called getSubpathname before, but turned out that was just something the RecursiveDirectoryIterator had…

So, had to grow my own… noting it here for others and the future:

class PathableRecursiveIteratorIterator
    extends RecursiveIteratorIterator
     * Gets the path to current node, i.e. each
     *   key "upwards", including self.
     * @param null|string $glue Optional $glue for implode().
     * @return array|string The keys, from root to self,
     *   as an array; or as a string if $glue is provided.

    public function getPath($glue = null)
        for($i = 0; $i < $this->getDepth(); $i++)
            $path[] = $this->getSubIterator($i)->key();

        $path[] = $this->key();

        return $glue !== null
            ? implode($glue, $path)
            : $path;

Based upon: StackOverflow

PHP: Delete directory recursively

function delete_directory($dir)
    if( ! file_exists($dir))

    $it = new RecursiveDirectoryIterator($dir);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($it as $file)

PHP: Simple directory recursion

Keep running into scenarios where I need to scan through a file system and it’s actually pretty simple if you just know what classes to use. So… note to self and others:

// This should return false if there is something you want excluded
function filter($file, $key, $iterator)
    $exclude = array('.git');
    return ! in_array($file->getFilename(), $exclude);

// Recursive directory iterator for current directory, ignoring dots
$it = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
// Wrapped by a filtering iterator with our filter function
$it = new RecursiveCallbackFilterIterator($it, 'filter');
// Wrapped by an iterator which automatically traverses children for us
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);

// And then just loop :)
foreach($it as $file)
    echo str_repeat("\t", $it->getDepth())
        . $file->getRealPath()
        . PHP_EOL;

This skips the annoying dots, properly excludes directories you don’t want and pretty much works the way it should.