Are there any best practices for optimizing PHP code when creating image galleries on a website?

When creating image galleries on a website using PHP, it's important to optimize the code for performance. One way to do this is by using lazy loading techniques to only load images when they are needed, reducing initial page load times. Additionally, resizing and compressing images before displaying them can help improve load times and reduce bandwidth usage.

// Lazy loading images in an image gallery
echo '<img src="placeholder.jpg" data-src="image1.jpg" class="lazy">';
echo '<img src="placeholder.jpg" data-src="image2.jpg" class="lazy">';
echo '<img src="placeholder.jpg" data-src="image3.jpg" class="lazy">';

// PHP code to resize and compress images before displaying
function resize_image($file, $w, $h) {
    list($width, $height) = getimagesize($file);
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($w, $h);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
    imagejpeg($dst, $file, 75);
}
resize_image('image1.jpg', 300, 200);
resize_image('image2.jpg', 300, 200);
resize_image('image3.jpg', 300, 200);