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;
?>
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
// 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.';
}
?>
$directory
variable specifies the folder where the images are stored (e.g., images/).glob()
function is used to get all image files (jpg
, jpeg
, png
, gif
) in the specified folder.array_rand()
function selects a random image from the array.<img>
tag that displays the selected random image.