How can the PHP code for randomly selecting and displaying images with links be optimized for efficiency?

The PHP code for randomly selecting and displaying images with links can be optimized for efficiency by storing the images and their corresponding links in an array, then using the array_rand() function to randomly select an index from the array. This eliminates the need for repetitive if statements and reduces the code complexity.

<?php
// Array of images with corresponding links
$images = array(
    "image1.jpg" => "link1",
    "image2.jpg" => "link2",
    "image3.jpg" => "link3"
);

// Randomly select an image and link
$randomIndex = array_rand($images);
$randomImage = $randomIndex;
$randomLink = $images[$randomIndex];

// Display the randomly selected image with link
echo "<a href='$randomLink'><img src='$randomImage' alt='Random Image'></a>";
?>