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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up