Home  >  Q&A  >  body text

How to implement random image display in a for loop in PHP

<p>I have a simple web page where I am trying to echo multiple images, my code is as follows</p> <p> <pre class="brush:html;toolbar:false;"><?php for($l=1;$l<=45;$l ){?> <div class="thumb" style="background-image: url(l<?=$l?>.jpg);"></div> <?php } ?></pre> </p> <p>So the pictures here are displayed in order from 1 to 45, but I want the pictures to be displayed in a random manner every time the page is loaded, can anyone tell me how to achieve this? Thank you in advance</p>
P粉852578075P粉852578075386 days ago474

reply all(1)I'll reply

  • P粉865900994

    P粉8659009942023-09-03 09:09:04

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

    reply
    0
  • Cancelreply