Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active February 10, 2021 21:01
Show Gist options
  • Save magnetikonline/10612342 to your computer and use it in GitHub Desktop.
Save magnetikonline/10612342 to your computer and use it in GitHub Desktop.
PHP reading of sub directories for files using recursion and generators.
<?php
// using generators (yield) to recursively read files from a source path
// more: http://www.php.net/manual/en/language.generators.php
foreach (readFileSubDir('~/testdir') as $fileItem) {
echo($fileItem . "\n");
}
function readFileSubDir($scanDir) {
$handle = opendir($scanDir);
while (($fileItem = readdir($handle)) !== false) {
// skip '.' and '..'
if (($fileItem == '.') || ($fileItem == '..')) continue;
$fileItem = rtrim($scanDir,'/') . '/' . $fileItem;
// if dir found call again recursively
if (is_dir($fileItem)) {
foreach (readFileSubDir($fileItem) as $childFileItem) {
yield $childFileItem;
}
} else {
yield $fileItem;
}
}
closedir($handle);
}
@psawiris
Copy link

thanks for the code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment