PHP

Recursive Directory Walker

admin by @admin ADMIN
16m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Yield every file under a directory using a generator and SPL's RecursiveIteratorIterator. Filter by extension or any other predicate without slurping all paths into memory first.
PHP
Raw
<?php
function walkFiles(string $root, ?callable $filter = null): Generator {
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($it as $file) {
        if (!$file->isFile()) continue;
        if ($filter && !$filter($file)) continue;
        yield $file->getPathname();
    }
}

// Every .php file under src/
foreach (walkFiles('src/', fn($f) => $f->getExtension() === 'php') as $path) {
    echo $path, PHP_EOL;
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.