开发者

Randomly picking out of an array in PHP

开发者 https://www.devze.com 2023-02-14 10:53 出处:网络
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 ran

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

精彩评论

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