Skip to main content
1 of 2
Mike Brant
  • 9.6k
  • 13
  • 23

Consider working with SPL's fileinfo and iterator classes (i.e. SplFileInfo, DirectoryIterator and FilterIterator, CallbackFilterIterator, etc) to build something a little more resilient.

Example:

$directoryIterator = new DirectoryIterator($directoryPath);
$imageFilter = function (SplFileInfo $splFileInfo) {
    return preg_match(
        '/^screenshot[0-9]{1,3}\.png$/',
        $splFileInfo->getFilename()
    ) ? true : false;
}
$filteredImageIterator = new CallbackFilterIterator(
     $directoryIterator,
     $imageFilter
);

foreach($filteredImageIterator as $image) { /* your code */ }
Mike Brant
  • 9.6k
  • 13
  • 23