Reputation: 143
So I'm using the following code to pull a random file from a folder and I would like to make it so there is never a chance of pulling up the current file again (ie: seeing the same image/document twice in a row).
How would I go about this? Thanks in advance!
function random_file($dir = 'destinations')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Upvotes: 0
Views: 374
Reputation: 10114
Store the last viewed filename in a cookie or in the session.
Here's how to do it with a cookie:
function random_file($dir = 'destinations') {
$files = glob($dir . '/*.*');
if (!$files) return false;
$files = array_diff($files, array(@$_COOKIE['last_file']));
$file = array_rand($files);
setcookie('last_file', $files[$file]);
return $files[$file];
}
Upvotes: 1
Reputation: 5201
If you want to present a fixed set of files in random order, then read all file names into an array, shuffle the array and then just use the array from start to end.
Upvotes: 0
Reputation: 6927
$picker = new FilePicker();
$picker->randomFile();
$picker->randomFile(); // never the same as the previous
--
class FilePicker
{
private $lastFile;
public function randomFile($dir = 'destinations')
{
$files = glob($dir . '/*.*');
do {
$file = array_rand($files);
} while ($this->lastFile == $file);
$this->lastFile = $file;
return $files[$file];
}
}
Upvotes: 1
Reputation: 355
Essentially: store the name of every file used in an array; every time you pull a new name, check whether it already exists in the array.
in_array()
will help you with that. array_push()
will help fill the "used files" array.
You could make the array a static one to have the list available whenever you call the function (instead of using global variables).
Upvotes: 0