vendredi 17 novembre 2017

Show randow image on each loop of foreach without it duplication in PHP

I have 10 images which is stored as an array. Also I have a foreach which generate me 10 items. My goal is to add random image from this array to each of my item that is generated by foreach, furthermore images shouldn't be duplicated.

For ex.:

1 item - img1.jpg;

2 item - img3.jpg;

3 item - img9.jpg... etc.

<?php
foreach (some logic here) {
     $images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
     $random_image = array_rand($images);
?>        
     <div class="grd">
         <div class="news-thum">
              <img src="<?php echo $images[$random_image]; ?>" />
         </div>
     </div>
<?php
}
?>

This code returns me random images for items but sometimes they are duplicated.

Is it possible to make it within PHP?




Aucun commentaire:

Enregistrer un commentaire