File system management is not the most common use case for PHP, but in writing a command line tool today I was surprised to find that PHP doesn't have a function to recursively remove a directory (I was expecting at least a flag for rmdir or unlink, but no, nothing).

I did a quick Google search, just to be sure, and found numerous other people asking this same question and a few rather long winded recursive functional solutions floating around.

No being much of a fan of functional programming (and also because really there is no excuse for it when PHP has had reasonable OOP and some fantastic stuff in the SPL for a long time now) I knocked together a much cleaner SPL based solution for recursively deleting a directory:

function recursiveRmDir($dir)
{
    $iterator = new RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $filename => $fileInfo) {
        if ($fileInfo->isDir()) {
            rmdir($filename);
        } else {
            unlink($filename);
        }
    }
}

I've obviously not added any checks to ensure that rmdir and unlink are successful, but this would be a simple addition and I really wanted to post this as an example of a nice modern way to use PHP rather than relying on old functional components.