I'm generating a sequence of pseudo random numbers with this code:
$seed = 1;
srand( $seed );
for($i=0; $i<10; $i++)
{
echo rand(0,100) . "\n";
}
exit(0);
The following code outputs always (on my machine)
84
39
79
[....]
77
28
55
Can I rely on the fact that the output of the above code will be always the same?
If not, what could make it change?
For example may different versions of PHP give different results?
Or PHP running on different operative systems?
If I run this code on Windows, I get a sequence of 99, 38, 79, 21, 75, 91, 42, 36, 47, 67. It's consistent against all versions, 32-bit or 64-bit on my Windows box.
Whereas if I run it on a Linux box I consistently get a sequence of 84, 39, 79, 80, 92, 19, 33, 77, 28, 55 no matter what version of PHP
So it isn't consistent between Operating Systems
However, if I use mt_srand()
and mt_rand()
instead of srand()
and rand()
then I do get consistence between Windows/Linux and different versions of PHP from 5.2 to 7.0
$seed = 1;
mt_srand( $seed );
for($i=0; $i<10; $i++)
{
echo mt_rand(0,100) . "\n";
}
exit(0);
consistently gives 58, 0, 72, 94, 100, 87, 70, 100, 86, 76