PHP - recursive function example

A recursive function is a function that calls itself.
/**
 * Use with care!
 * Recursively delete a file or directory.
 * @param string $path
 */
function recursiveRemove($path)
{
    if (is_dir($path)) {
        foreach (scandir($path) as $entry) {
            if (!in_array($entry, ['.', '..'])) {
                recursiveRemove($path . DIRECTORY_SEPARATOR . $entry); // calls itself
            }
        }
        rmdir($path);
    }
    if (is_file($path)) unlink($path);
}

recursiveRemove('/path/to/dir');

source: https://stackflow.cc/post/1ec29a2f-c9b9-645a-a28f-0050563fb25b

Comments