pic random images from array

94 views Asked by At

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

2

There are 2 answers

2
vaso123 On BEST ANSWER

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)];
2
empiric On

You can do something like this:

$dir = "bg_photos/less_saturation/";

if (is_dir($dir)) {
    $files = array_diff(scandir($dir), array('..', '.'));

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