Search code examples
phparraysshufflerandom-seed

Shuffle array with a repeatable/predictable result based on a seed integer


I have 6 users and I want to shuffle an array for each user but with a particular logic.

I have array like this:

$a = array(1, 6, 8);

When shuffled it gives me these results:

shuffle($a); //array(8,6,1) or array(8,1,6) or ...

I want to shuffle the array for a specific user and have it be the same every time for that user:

  • for user that has id equals 1, give array like this array(6,8,1) every time
  • for user that has id equals 2, give array like this array(1,8,6) every time

In other words, I want to shuffle an array with private key!


Solution

  • If you provide a seed to the random number generator it will randomize the same way for the same seed (see the version differences below). So use the user id as the seed:

    srand(1);
    shuffle($a);
    

    Output for 7.1.0 - 7.2.4

    Array
    (
        [0] => 1
        [1] => 8
        [2] => 6
    )
    

    Output for 4.3.0 - 5.6.30, 7.0.0 - 7.0.29

    Array
    (
        [0] => 6
        [1] => 1
        [2] => 8
    )
    

    Note: As of PHP 7.1.0, srand() has been made an alias of mt_srand().

    This Example should always produce the same result.