Shuffle image order in php

I have the following images that I use for a carousel. Every time a page loads, I want them to be in a different order. I was just thinking of ordering numbers with a random number generator, but then I’m not sure how to make the numbers be used only once. If this can be done in a loop so that it expands, that would be great.

See the static code below, all images are named the same except for the number at the end

<div class="image-entry"> <img src="/images/carousel-1.jpg" /> </div> <div class="image-entry"> <img src="/images/carousel-2.jpg" /> </div> <div class="image-entry"> <img src="/images/carousel-3.jpg" /> </div> <div class="image-entry"> <img src="/images/carousel-4.jpg" /> </div> 

thanks!

+7
source share
4 answers

There is a shuffle() function for this:

 $images = array ( '/images/carousel-1.jpg', '/images/carousel-2.jpg', '/images/carousel-3.jpg', '/images/carousel-4.jpg', ); shuffle($images); // the magic foreach ($images as $image) { echo '<div class="image-entry">'; echo "\t" . '<img src="' . $image . '" />'; echo '</div>'; } 
+10
source

Assuming you know how many images (say 4) you want, and all the images up to this number are valid and start with 1:

 <?php $images = range(1, 4); shuffle($images); foreach ($images as $_) { echo <<<HTML <div class="image-entry"> <img src="/images/carousel-$_.jpg" /> </div> HTML; } 
+2
source

Create an array of number / image names, and then shuffle the array, and then output it like this.

 $images[0] = 'car-1.jpg'; $images[1] = 'car-2.jpg'; $images[2] = 'car-3.jpg'; shuffle($images); foreach($images as $img){ echo '<img src="'.$img.'" />'; } 

You can tailor the above code to suit your needs.

+1
source
 <?php $imageArr = glob( rtrim( $_SERVER['DOCUMENT_ROOT'] , '/' ).'/images/carousel-*.jpg' ); shuffle( $imageArr ); $outPattern = '<div class="image-entry"><img src="%s" /></div>'; foreach( $imageArr as $carImage ) echo sprintf( $outPattern , $carImage )."\n"; 

The advantages of this solution are that it will automatically detect all images with the name carousel-X.jpg in the image folder and use them in the carousel.

Or even:

 <?php $imageArr = glob( rtrim( $_SERVER['DOCUMENT_ROOT'] , '/' ).'/images/carousel-*.jpg' ); shuffle( $imageArr ); if( count( $imageArr ) ){ echo '<div class="image-entry"><img src="'.implode( '" /></div><div class="image-entry"><img src="' , $imageArr ).'" /></div>'; }else{ echo '<!-- No Images in Array //-->'; } 
+1
source

All Articles