Randomize a PHP array with a seed? -


i'm looking function can pass array , seed in php , "randomized" array. if passed same array , same seed again, same output.

i've tried code

 //sample array $test = array(1,2,3,4,5,6); //show array print_r($test);  //seed random number generator mt_srand('123'); //generate random number based on echo mt_rand(); echo "\n";  //shuffle array shuffle($test);  //show results print_r($test);  

but not seem work. thoughts on best way this?

this question dances around issue it's old , nobody has provided actual answer on how it: can randomize array providing seed , same order? - "yes" - how?

update

the answers far work php 5.1 , 5.3, not 5.2. happens machine want run on using 5.2.

can give example without using mt_rand? "broken" in php 5.2 because not give same sequence of random numbers based off same seed. see php mt_rand page , bug tracker learn issue.

you can use array_multisort order array values second array of mt_rand values:

$arr = array(1,2,3,4,5,6);  mt_srand('123'); $order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr))); array_multisort($order, $arr);  var_dump($arr); 

here $order array of mt_rand values of same length $arr. array_multisort sorts values of $order , orders elements of $arr according order of values of $order.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -