How can PHP arrays be utilized to efficiently store and retrieve image files from a directory for display on a website?

When displaying multiple image files on a website, it's efficient to use PHP arrays to store the file names from a directory. This allows for easy retrieval and display of images without hardcoding each file name. By looping through the array, you can dynamically generate image tags for each file.

<?php
// Directory where image files are stored
$directory = "images/";

// Get all file names from the directory
$files = scandir($directory);

// Filter out non-image files
$images = array_filter($files, function($file) {
    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    return in_array($ext, $imageExtensions);
});

// Display images on the website
foreach($images as $image) {
    echo "<img src='{$directory}{$image}' alt='{$image}'>";
}
?>