How to use the random function correctly in php?
Good afternoon. I'm teaching pcp, I ran into this problem: there is a script that generates 1 random number. But on the server, the time is updated every few seconds, so if you quickly over-execute the script several times, the generator generates the same number. How do I get around this problem?
1
2 answers
mt_rand()
the most proven and reliable function that returns a pseudo-random number does not depend on the server in any way and can not generate the same numbers because of the server, use this function and you will almost a real random number.
You can also use the more modern function random_int
, but it has its own nuances that the first function does not have.
1
Author: Евгений Иванов, 2018-04-23 13:08:34
$array = [];
function getRandom($min = 0, $max = 9999, $try = 0) use ($array)
{
$int = mt_rand($min, $max);
if (in_array($int, $array) || $try > 5) {
return getRandom($min, $max, ++$try);
}
return $int;
}
Instead of $array
, you can take/store numbers in the base
0
Author: J. Doe, 2018-04-23 13:49:30