简体   繁体   中英

how to display image randomly inside for loop in php

i have a simple webpage where i am trying to echo multiple images, my code is like below

 <?php for($l=1;$l<=45;$l++){?> <div class="thumb" style="background-image: url(l<?=$l?>.jpg);"></div> <?php }?>

so here the images are displayed fine in an order from 1 to 45, but what i want is images to display randomly everytime the page is loaded, can anyone please tell me how to accomplish this, thanks in advance

As mentioned in the comments, just create an array and shuffle it.

$images = [];
for ($l = 1; $l <= 45; $l++) {
    $images[] = "<div class='thumb' style='background-image: url(l{$l}.jpg);'></div>";
}
shuffle($images);
echo implode("\n", $images);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM