What are some best practices for optimizing PHP scripts to improve the performance of image galleries, especially when dealing with large numbers of images?

When dealing with large numbers of images in an image gallery, it is important to optimize PHP scripts to improve performance. One way to do this is by implementing lazy loading, which loads images only when they are in view, reducing the initial load time of the gallery. Additionally, using caching mechanisms such as storing image metadata in a database or caching images on the server can help reduce the load on the server and improve overall performance.

// Lazy loading implementation in PHP for image gallery
echo '<div class="image-gallery">';
foreach ($images as $image) {
    echo '<img class="lazy" data-src="' . $image['src'] . '" alt="' . $image['alt'] . '">';
}
echo '</div>';
```

```php
// Caching images in PHP for image gallery
function get_cached_image($image_id) {
    $cache_key = 'image_' . $image_id;
    $cached_image = apc_fetch($cache_key);

    if (!$cached_image) {
        $image_data = fetch_image_data_from_database($image_id);
        $cached_image = generate_image_html($image_data);
        apc_store($cache_key, $cached_image);
    }

    return $cached_image;
}