Randomly picking out of an array in PHP

2019-04-01 04:37发布

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.

标签: php random
3条回答
虎瘦雄心在
2楼-- · 2019-04-01 05:01

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

查看更多
姐就是有狂的资本
3楼-- · 2019-04-01 05:13

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);
...
查看更多
我只想做你的唯一
4楼-- · 2019-04-01 05:14

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.

查看更多
登录 后发表回答