You can explicitly seed the random number generator with the same value each time:
$list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
srand(123456);
shuffle($list);
print_r($list);
This will result in the same shuffle each time the script is run.
Why this works:
array_shuffle()
uses the same random number generator that rand()
does. If you do not manually seed that random number generator with srand()
, PHP does it for you, with a random seed. Thus, if you simply call array_shuffle()
or rand()
, you get a different output every time. This is how it’s almost always used.
Now, if you want reproduceable random results, you can use srand()
to initialize the random number generator by manually seeding it with a known value. As long as the random number generator is seeded with the same value, it will always produce the same results, even across different runs of the same script. Video games often use this technique (e.g., “Enter your game number”) to allow you play the same random game over again.
It might help if you think of it this way: the computer doesn’t give you a truly random number, it has billions of pre-built series of random numbers that are infinitely long. When you call array_shuffle()
the computer picks one of those series for you. But if you precede that call with srand(123456)
, then you’re saying, “Whenever you need a random number, use series number 123456.” The value you use doesn’t matter, as long as it’s the same each time you run the script.
12
solved Generate random array that is fixed – PHP [closed]