PHP

Display a random image

London
London

Method 1 (output above):

Create an array of images and use the array_rand() function to randomly select an image from the array:

<?php
$randomArray = array(

'<figure><img src="images/hamburg.jpg" alt="Hamburg">
<figcaption>Hamburg</figcaption></figure>',

'<figure><img src="images/london.jpg" alt="London">
<figcaption>London</figcaption></figure>',

'<figure><img src="images/rome.jpg" alt="Rome">
<figcaption>Rome</figcaption></figure>'

);

$displayAtRandom = 
$randomArray[array_rand($randomArray)];
echo $displayAtRandom;
?>

Method 2 (output below):

Random Image Demo

Place the images you want to display randomly in a folder, such as images/. For example, the images might be image1.jpg, image2.jpg, image3.jpg, etc. and then use the array_rand() function to randomly select an image from the array:

PHP

<?php
// Define the path to the images folder:
  $directory = 'images/';

// Get all the image files in the folder:
  $images = glob($directory . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

// Check if there are any images in the folder:

if (count($images) > 0) {
// Select a random image from the array
$randomImage = $images[array_rand($images)];
  
// Display the image:

echo '' . $randomImage . '';
} 

else {
echo 'No images found in the directory.';
}
?>

Explanation:

  • Directory Path: The $directory variable specifies the folder where the images are stored (e.g., images/).
  • Image Selection: The glob() function is used to get all image files (jpg, jpeg, png, gif) in the specified folder.
  • Random Image: The array_rand() function selects a random image from the array.
  • Display the Image: The echo statement is used to output an HTML <img> tag that displays the selected random image.