I have the following PHP code which produces random numbers using rand()
and to unsure there are no duplicates until the max int, a session which tracks what numbers have been used. The max should never get too high so speed if the randoms are larger is not a problem and this sort of works fine so far. HOWERVER...
function random($min,$max) {
if(count($_SESSION["randoms"])==5) {
unset($_SESSION["randoms"]);
}
$rand = rand($min,$max);
echo "Chosen Random: $rand<br>";
if(@in_array($rand,$_SESSION["randoms"]) && count($_SESSION["randoms"])!=0) {
echo "<strong>In Array: </strong>Do It Again<br>\n";
random($min,$max);
}
else {
echo "<strong>All Good </strong> Return $rand as number and include in array!<br>\n";
$_SESSION["randoms"][] = $rand;
return $rand;
}
}
I have a few echo blocks in there to help debug. Everything works fine however when the random is called on the recursive it continues going until it finds a number not in the array and echos "All Good" and adds it to the array, but doesn't return it. If the number was not in the array to begin with it returns it fine. I am confused as to why it will echo the "All Good" and add it to the array but not return it to use in the rest of the script.