Home » Php » random – shuffle order of images in php

random – shuffle order of images in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

See the static code below, all the 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!

How to&Answers:

There is a function for that, shuffle():

$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>';
}

Answer:

Assuming that you know how many images (say 4) you want and that all images up to that 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;
}

Answer:

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

$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 adapt the above code to suit your needs.

Answer:

<?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 benefits of this solution being that it will automagically detect all images called carousel-X.jpg in the images 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 //-->';
}