DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on • Edited on

3

How to list files recursively in a directory with PHP iterators

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;
}
Enter fullscreen mode Exit fullscreen mode

Usage

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

Want the list as an array?

$files = iterator_to_array(filesIn('app/'));
Enter fullscreen mode Exit fullscreen mode

Don't forget to leave a like!

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay