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...