Home > Mobile >  how to display image randomly inside for loop in php
how to display image randomly inside for loop in php

Time:08-08

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  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

CodePudding user response:

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);
  • Related