0

this is my code for to randomly echo images.

   <?php

    $imagesDir = "socimages/Badminton/";
    $images = glob($imagesDir . '*.{jpg,png,gif}', GLOB_BRACE);
    $randomImage = $images[array_rand($images)]; 
    ?>
    <img src="<?php echo $randomImage[0]?>">
    <img src="<?php echo $randomImage[1]?>">

It does not work if I specify each element in the array, so I was wondering how can I make it so that it will print random images but images cannot be the same, if I ignore the elements, it will print out the two images but the two images will be identical, if I reload the page, the image will change but both images will remain the same.

FangXIII
  • 71
  • 4
  • 10
  • Here's a similar topic : http://stackoverflow.com/questions/11876075/php-generate-random-image-from-a-directory – IndieTech Solutions Mar 07 '15 at 14:37
  • If you want to preserve the information which images have already been picked between requests, then you have to store that information. Requests are independent otherwise. Take a look at session variables. – arkascha Mar 07 '15 at 14:50

1 Answers1

0

array_rand can get 2 parameters. The second one is the number of random elements to get.

Try this:

<?php
// ...
$randomImage = array_rand($images, 2);
?>
<img src="<?php echo $images[$randomImage[0]]?>">
<img src="<?php echo $images[$randomImage[1]]?>">
Giacomo M
  • 4,450
  • 7
  • 28
  • 57