PHP

Display a random image

About this snippet

This code snippet demonstrates two different methods to output a random image from a predefined list or directory. The first approach displays a random image by selecting one from a predefined array of HTML image elements. The second approach involves loading all images from a folder dynamically, then selecting one at random to display. These techniques are useful for applications such as image galleries, random background generators, or surprise image features.

Method 1
Rome
Rome
PHP
<?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
Random Image Demo
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.