user1153594
user1153594

Reputation: 281

PHP - get random image from multiple folders

I am trying to figure out the best way, using PHP, to pull a random image from multiple sub-folders on my site. I would use the RecursiveDirectoryIterator to iterate through the subfolders and extract images, but am wondering how to handle the randomisation and how to do it efficiently. Any advice on how to go about this?

Upvotes: 1

Views: 1498

Answers (3)

pät
pät

Reputation: 543

function get_images($root) {

    $r = array();
    foreach(glob("$root/*") as $n) {
        if (is_dir($n)) {
            $r = array_merge($r, get_images($n));
        } else {
           $r[] = $n;
        }
    }

    return $r;
}

$files = get_images('foo');
shuffle($files);
echo $files[0];

Upvotes: 3

Basti
Basti

Reputation: 4042

Load all the full $paths into an $array and select mt_rand(0, count($array)-1).

You might want to cache your list as long as it does not change, to avoid re-iterating over your directories.

Upvotes: 0

Peter Kiss
Peter Kiss

Reputation: 9319

Create a random number for the iteration endpoint (while $i < 10). Before this you can create another random session to choose the directory.


Read all images into an array then pick a random index.

Upvotes: 3

Related Questions