Search code examples
phparraysscandir

pic random images from array


So I have this code that randomly pics an image out of the array provided:

$bg = array('1.jpg', '2.jpg', '2.jpg',); // array of filenames

$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen

But I would like to get the images from a folder no matter the name and how many there are.

I've tried this :

$dir = "bg_photos/less_saturation/";

$exclude = array( ".","..");
if (is_dir($dir)) {
    $files = scandir($dir);
    foreach($files as $file){
        if(!in_array($file,$exclude)){
            echo $file;         
            $bg = array($file); // array of filenames
            $i = rand(0, count($bg)-1); // generate random number size of the array
            $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
        }
    }
}

But this only ever gives me the last image in the array ... Can anyone help ?

Cheers

Chris


Solution

  • You can use this code. This is collect all the files, exept . and .., into an array, and get a random item from the array.

    $dir = "bg_photos/less_saturation/";
    $exclude = array( ".","..");
    $bg = array();
    if (is_dir($dir)) {
        $files = scandir($dir);
        foreach($files as $file){
            if(!in_array($file,$exclude)){
                echo $file;         
                //Use as an array
                $bg[] = $file; // array of filenames
            }
        }
    }
    $selectedBg = $bg[array_rand($bg)];