Randomly picking out of an array in PHP

2019-04-01 04:56发布

问题:

I have an array that has values like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is to randomly one value, perhaps 6. Then I want to pick a random value excluding 6 (so no doubles). Then a random value excluding the last two, all from inside an array. Any help? I'm trying to do this without while loops but if they are necessary then so be it.

回答1:

I suggest the following:

# pick a random key in your array
$rand_key = array_rand($your_array);

# extract the corresponding value
$rand_value = $your_array[$rand_key];

# remove the key-value pair from the array
unset($your_array[$rand_key]);

See: array_rand, unset.



回答2:

Shuffle the array first and then use it as a stack:

$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);

// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...


回答3:

I would probably shuffle the array and get the first/last x value



标签: php random