I need to shuffle an array based on a seed number so I can get the same shuffle if I need it.
For example:
1. print_r( shuffleIt( $array, 2 ) );
2. print_r( shuffleIt( $array, 6 ) );
3. print_r( shuffleIt( $array, 2 ) );
- and 3. would show the same shuffled array but different than 2.
I found this function googling:
function entropy( $array, $sort_seed ) {
mt_srand( $sort_seed );
$order = array_map( create_function( '$val', 'return mt_rand( );' ), range( 1, count( $array ) ) );
array_multisort( $order, $array );
return $array;
}
It works fine on my pc with php-cli, I always get the same array for each different sort_seed I use, but when I uploaded it to a server, I get different arrays every time even when I am using the same sort_seed.
How could I get always the same shuffled array when using the same sort_seed?
btw. I need to preserve keys or sort a multidimensional array so I can store the key there.
If you need it on any pc, you need a random number generator that works the same across computers. I looked up one pseudo-random-number generator that might be suitable for you from the Random Number Generation Wikipedia page and put it into a class so you can seed it.
I don’t know for what you need it, but this just might suit your needs. It’s independent to system configuration:
Note: This might behave differently between 32/64 bit systems, especially as PHP differs here for integers and overflows between windows and unix. You might want offset at the signed minimum for 32 bit integers in PHP instead of 0 as it is now, to switch the implementation to gmp or just reduce the size by one bit.
Usage Example 32 bit reported to work by ekke from netherlands