Kody
Kody

Reputation: 762

Random order of readdir

How would I modify my PHP code below to output all the files in the directory, but to put them in a random order that changes each time the page gets reloaded?

if ($handle = opendir("files/slideshow/")) {
    while (false !== ($slide = readdir($handle))) {
        if ($slide != "." && $slide != "..") {
            echo "<img style=\"background:url('/files/slideshow/{$slide}');background-repeat:no-repeat;\" src=\"/files/images/i.png\"/>";
            $value = "1";
        }
    }
    closedir($handle);
}

Upvotes: 0

Views: 833

Answers (1)

sectus
sectus

Reputation: 15464

Use more shorter way with glob with adding array shuffle.

$files = glob('files/slideshow/*'); // or even 'files/slideshow/*.png'
shuffle($files); 
foreach ($files as $slide)
    {
    echo "<img style=\"background:url('/files/slideshow/{$slide}');background-repeat:no-repeat;\" src=\"/files/images/i.png\"/>";
    $value = "1";
    }

Upvotes: 3

Related Questions