What are some potential pitfalls of using foreach loops to read directories and count images in PHP?

Using foreach loops to read directories and count images in PHP can be inefficient and error-prone, especially when dealing with a large number of files. It can lead to performance issues and potential memory leaks. To solve this, it's recommended to use PHP's DirectoryIterator class, which provides a more efficient and reliable way to iterate over directory contents.

$directory = new DirectoryIterator('/path/to/directory');
$imageCount = 0;

foreach ($directory as $fileInfo) {
    if ($fileInfo->isFile() && $fileInfo->getExtension() === 'jpg') {
        $imageCount++;
    }
}

echo "Number of images in the directory: " . $imageCount;