Choose 3 different random values from an array

2019-06-15 03:58发布

I have an array of 30 values and I need to extract from this array 3 different random values. How can I do it?

3条回答
你好瞎i
2楼-- · 2019-06-15 04:30

I'm not sure why bother using array_rand() at all as it's just an extra function call for seemingly no reason. Simply shuffle() and slice the first three elements:

shuffle($array);
print_r(array_slice($array, 0, 3));
查看更多
混吃等死
3楼-- · 2019-06-15 04:36

use shuffle($array) then array_rand($array,3)

查看更多
淡お忘
4楼-- · 2019-06-15 04:50

Shamelessly stolen from the PHP manual:

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

http://us2.php.net/array_rand

Note that, as of PHP 5.2.10, you may want to shuffle (randomize) the keys that are returned via shuffle($rand_keys), otherwise they will always be in order (smallest index first). That is, in the above example, you could get "Neo, Trinity" but never "Trinity, Neo."

If the order of the random elements is not important, then the above code is sufficient.

查看更多
登录 后发表回答