How to display image randomly inside for loop in php?

by tressie.damore , in category: PHP General , 10 months ago

How to display image randomly inside for loop in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 10 months ago

@tressie.damore 

To display images randomly inside a for loop in PHP, you can follow these steps:

  1. Create an array of image URLs or image file names.
  2. Shuffle the array using the shuffle() function to randomize the order of the images.
  3. Iterate through the array using a for loop.
  4. Inside the loop, use the echo statement to display an img tag with the current image URL or file name.


Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php
// Step 1: Create an array of image URLs or file names
$images = array(
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    // Add more images as needed
);

// Step 2: Shuffle the array
shuffle($images);

// Step 3: Iterate through the array using a for loop
for ($i = 0; $i < count($images); $i++) {
    // Step 4: Display an img tag with the current image URL or file name
    echo '<img src="' . $images[$i] . '" alt="Random Image">';
    echo '<br>'; // Add a line break if needed
}
?>


This code will randomly display images from the array inside the for loop. Note that in the <img> tag, the src attribute is set to the current image URL or file name.