1

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?

1

3 Answers 3

3
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];
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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.

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.