What could be a more efficient way to iterate through subfolders and display images in PHP?

When iterating through subfolders to display images in PHP, a more efficient way would be to use the RecursiveDirectoryIterator and RecursiveIteratorIterator classes. These classes allow you to recursively iterate through directories and subdirectories in a more streamlined manner, reducing the need for nested loops and improving code readability.

$directory = new RecursiveDirectoryIterator('path/to/directory');
$iterator = new RecursiveIteratorIterator($directory);

foreach ($iterator as $file) {
    if ($file->isFile() && in_array($file->getExtension(), ['jpg', 'jpeg', 'png', 'gif'])) {
        echo '<img src="' . $file->getPathname() . '" alt="' . $file->getFilename() . '">';
    }
}