Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active October 10, 2022 02:42
Show Gist options
  • Save tsprates/85901df530401193f7148fd19df7ba7a to your computer and use it in GitHub Desktop.
Save tsprates/85901df530401193f7148fd19df7ba7a to your computer and use it in GitHub Desktop.
List all files in a directory and their respective subdirectories recursively
<?php
/**
* List all files in a directory and their respective subdirectories recursively.
*
* @param string $directory
* @return null|Generator
*/
function scandir_all(string $directory): ?Generator
{
if (!is_dir($directory)) {
return;
}
$files = scandir($directory);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$absolutePath = realpath($directory) . DIRECTORY_SEPARATOR . $file;
if (is_dir($absolutePath)) {
yield from scandir_all($absolutePath);
continue;
}
yield $absolutePath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment