0

I have a php code which uses every image in a folder and echos the url on my page.

what i need help with is making the php code randomize the list of urls each time the page is loaded.

The code that i have is:

<?php 
 if ($handle = opendir('images')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
      {
            $thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
          }
       }
  closedir($handle);
  }
?>
<?=$thelist?>

many thanks

1
  • So, what is the problem and what do you want? Commented Jan 12, 2013 at 23:20

4 Answers 4

2

Easiest solution would be to put all filenames into an array and then use shuffle() to mix it up. Then you can iterate over the array and output the images. It should look something like this:

<?php 
 $thelist = "";
 if ($handle = opendir('images')) {
   $images = array();
   while (false !== ($file = readdir($handle))) {
      if ($file != "." && $file != "..") {
            array_push($images, 'images/'.$file);
      }
   }
   closedir($handle);
   shuffle($images);
   foreach ($images as $image) {
      $thelist .= '<div data-delay="5"><img src="'.$image.'"></div>';
   }
   echo $thelist;
 }
?>

By using glob() instead of opendir() you could shorten the code significantly, as glob() returns an array and then you only would need to shuffle that one.

Sign up to request clarification or add additional context in comments.

Comments

0

put your file links into an array and shuffle it with the function shuffle()

<?php 

if ($handle = opendir('images')) {
    $fileTab = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $fileTab[] = $file; 
        }
    }
    closedir($handle);
    shuffle($fileTab);
    foreach($fileTab as $file) {
        $thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
    }
}
?>
<?=$thelist?>

Comments

0

Instead of directly creating divs in the while loop, use it only to store all urls in an Array. Then shuffel that array, and use a foreach loop in order to populate $thelist.

Comments

0

Why don't you use glob()?

$images = glob('images/*.{jpg,png,gif}', GLOB_BRACE);

shuffle($images);

foreach($images as $image) {
    echo '<div data-delay="5">
              <img src="', $image ,'">
          </div>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.