开发者

Randomly picking out of an array in PHP

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 withou开发者_如何学Got while loops but if they are necessary then so be it.


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.


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);
...


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜