Reputation:
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:
user
that has id equals 1, give array like this array(6,8,1) every time 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!
Upvotes: 2
Views: 272
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
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