loading...

How to list files recursively in a directory with PHP iterators

bdelespierre profile image Benjamin Delespierre ・1 min read

This snippet is so useful to write custom commands that checks my code.

Code

function filesIn(string $path): \Generator
{
    if (! is_dir($path)) {
        throw new \RuntimeException("{$path} is not a directory ");
    }

    $it = new \RecursiveDirectoryIterator($path);
    $it = new \RecursiveIteratorIterator($it);
    $it = new \RegexIterator($it, '/\.php$/', \RegexIterator::MATCH);

    yield from $it;
}

Usage

foreach (filesIn('app/') as $file) {
    $contents = file_get_contents($file->getPathname());
}

Want the list as an array?

$files = iterator_to_array(filesIn('app/'));

Don't forget to leave a like!

Posted on by:

bdelespierre profile

Benjamin Delespierre

@bdelespierre

CTO at AddWorking, I write Laravel snippets all the time

Discussion

markdown guide