Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading