Only return files with the directory iterator

I’ve used DirectoryIterator a bit recently to find files. One thing I continually need to do when I finally loop through the results is exclude directories, ‘.’, and ‘..’. Today I found out about CallbackFilterIteratorwhich will allow you to filter items in an iterator. So rather than including logic in the loop to exclude directories I can just create my iterator like so:

$files = new CallbackFilterIterator(
    new DirectoryIterator('/path/to/directory/'),
    function ($current, $key, $iterator) {
        return !$current->isDir() and !$current->isDot();

foreach ($files as $file) {
	echo $file->getFilename() . '<br />';

I like that $files now includes just files like I needed and I don’t need to muck things up down the line by checking for directories when I use the loop.

Leave a Reply

Your email address will not be published. Required fields are marked *