How can the script be optimized to efficiently store and retrieve images from directories using arrays in PHP?

To efficiently store and retrieve images from directories using arrays in PHP, you can optimize the script by using the glob() function to retrieve all image files in a directory and store them in an array. This allows for easy access and manipulation of the image files without having to individually specify each file.

// Retrieve all image files from a directory and store them in an array
$images = glob('path/to/directory/*.jpg');

// Loop through the array to display or manipulate the images
foreach ($images as $image) {
    echo '<img src="' . $image . '" alt="Image">';
}