Question

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);
}
Was it helpful?

Solution

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";
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top