
Method 1 (output above):
Create an array of images and use the array_rand()
function to randomly select an image from the array:
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 (output below):
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.
Arithmetic operators
Background that adapts to the current season
Calculate the similarity of text
Comparison operators
Count page views in a session
Display a random image
Display a random text
Display array values
Display a time based greeting
Display the current copyright year
Display current date
Display the current date in another language
Display date based on system language settings
Quiz with input fields
Quiz with input fields, multi-steps
Quiz with radio buttons
Quiz with radio buttons, multi-steps
Redirect users to another page
Retrieve checkbox values
Retrieve form input values
Retrieve the value of the selected option
Retrieve the value of the star rating
Store the value of a radio button in a session
Truncate a string to a specified width
Word Wrap