What I want to achieve is to make a webpage which every time generates different content from MySQL DB. But when I use the rand() function, some options can repeat. So what I want to do is make rand() function with dynamic array "exceptions" that updates every time when the webpage content is generated, so every option is displayed to user only once.
Let’s say I have 5 different options:
1,2,3,4,5
When the rand() function chooses 3 next time there will be no chance for getting 3 as a result..
function randWithout($from, $to, array $exceptions) {
sort($exceptions);
$number = rand($from, $to - count($exceptions));
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++;
} else {
break;
}
}
return $number;
}
$exceptions = array("3","4");
$random = randWithout(1, $num_rows, $exceptions);
This does what I want, but I want the array "$exceptions" to update every time.
Is there a way to do this by using sessions or some other options? I don’t want to use another MySQL table. I want it to be fast and simple.
Use Sessions. Sessions are used for data persistence. start your php file like this:
Save your exceptions in a session variable :
Every time user visits a page add that to the session.
suppose you want to add ‘5’ to it.
Hers updated code