How can the PHP code be optimized to check for the existence of both jpg and gif images before displaying them in the img tag?

To optimize the PHP code to check for the existence of both jpg and gif images before displaying them in the img tag, you can use the file_exists() function to check if the image files exist. This ensures that only existing image files are displayed in the img tag.

<?php
$jpg_image = "image.jpg";
$gif_image = "image.gif";

if (file_exists($jpg_image) && file_exists($gif_image)) {
    echo "<img src='$jpg_image' alt='JPG Image'>";
    echo "<img src='$gif_image' alt='GIF Image'>";
} else {
    echo "One or both images do not exist.";
}
?>