user9458061
user9458061

Reputation:

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:

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

Upvotes: 2

Views: 272

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

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.

Upvotes: 2

V.Rangelov
V.Rangelov

Reputation: 29

Quoting php.net:

This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

Whatever you are trying to get as a result, you cannot use shuffle because it will randomly give you some order.

If you want to randomly do an order to array, based on some criteria use usort:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
}
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

Now get the logic in the cmp function...

Upvotes: -1

Related Questions