Skip to content
PHP Logo

How can randomization be implemented in PHP to display different images upon each page load?

To display different images upon each page load in PHP, you can create an array of image file paths and then use the rand() function to randomly select an image from the array each time the page is loaded.

php
<?php
// Array of image file paths
$images = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    // Add more image paths here
];

// Get a random index from the array
$randomIndex = array_rand($images);

// Display the randomly selected image
echo '<img src="' . $images[$randomIndex] . '" alt="Random Image">';
?>