Reputation: 159
How can I make the php shuffle function use a seed, so that when I use the same seed, the shuffle function will output the same array. I read that shuffle is automatically seeded. Is there a way to get the seed of that shuffle used, or how can I create/mimic shuffle with a custom seed?
Upvotes: 0
Views: 2527
Reputation: 8325
PHP does not have shuffling with seeding, but you can do this instead:
$an_array = array('a','b','c','d');
$indices = array(0,1,2,3);
// shuffle the indices and use them as shuffling seed
shuffle($indices);
// then whenever you want to produce exactly same shuffle use the pre-computed shuffled indices
function shuffle_precomputed($a, $shuffled_indices)
{
$b = $a; // copy array
foreach ($shuffled_indices as $i1=>$i2) $a[$i2] = $b[$i1];
return $a;
}
use like this:
$shuffled_array = shuffle_precomputed($an_array, $indices);
You can even use the factoradic number system to transform the $shuffled_indices
array to/from a unique integer number that can be used as a unique seed, then simply compute the shuffle from the factoradic number to be used in shuffle_precomputed
function.
For additional shuffle
variations for PHP you may want to see:
Upvotes: -1
Reputation: 212412
You can't retrieve the seed used by shuffle, but you can simulate shuffle and fix your own seed:
$array = range(1, 10);
function seededShuffle(array &$array, $seed) {
mt_srand($seed);
$size = count($array);
for ($i = 0; $i < $size; ++$i) {
list($chunk) = array_splice($array, mt_rand(0, $size-1), 1);
array_push($array, $chunk);
}
}
$seed = date('Ymd');
seededShuffle($array, $seed);
var_dump($array);
This will set a different seed each day, but throughout the day it will use the same seed and shuffle the array in the same order; tomorrow will be a different random shuffle to today
For today (6th June 2015), the sequence should be
3, 6, 9, 2, 7, 1, 8, 5, 10, 4
Upvotes: 5