How can PHP code be optimized to handle the display of a large number of images more efficiently?

When handling the display of a large number of images in PHP, it is important to optimize the code to improve performance. One way to do this is by using lazy loading techniques, which only load images as they are needed, reducing the initial load time of the page. Additionally, caching images can help reduce server load and improve load times for subsequent visits.

<?php
// Lazy loading images
$images = array("image1.jpg", "image2.jpg", "image3.jpg", ...);

echo "<div class='image-container'>";
foreach ($images as $image) {
    echo "<img src='placeholder.jpg' data-src='$image' class='lazy-load'>";
}
echo "</div>";

// Caching images
function displayImage($image) {
    $cache_folder = "image_cache/";
    $cache_file = $cache_folder . $image;

    if (!file_exists($cache_file)) {
        // Load image from source and save to cache
        $source_image = file_get_contents($image);
        file_put_contents($cache_file, $source_image);
    }

    echo "<img src='$cache_file'>";
}

// Usage
displayImage("image1.jpg");
?>