Finding files and directories using recursion
Quite often, we need to find all the files inside a directory. This includes all subdirectories inside it and also directories inside those subdirectories. As a result, we need a recursive solution to find the list of files from the given directory. The following example will show a simple recursive function to list all the files in a directory:
function showFiles(string $dirName, Array &$allFiles = []) {
$files = scandir($dirName);
foreach ($files as $key => $value) {
$path = realpath($dirName . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$allFiles[] = $path;
} else if ($value != "." && $value != "..") {
showFiles($path, $allFiles);
$allFiles[] = $path;
}
}
return;
}
$files = [];
showFiles(".", $files);The showFiles function actually takes a directory and first scans the directory to list all the files and directories under it. Then,...