php获取两个不同的随机数组元素

cre*_*ivz 13 php arrays random

从阵列

 $my_array = array('a','b','c','d','e');
Run Code Online (Sandbox Code Playgroud)

我想得到两个不同的随机元素.

使用以下代码:

 for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;
 }
Run Code Online (Sandbox Code Playgroud)

它可以得到两次相同的字母.我需要阻止这一点.我想总是得到两个不同的数组元素.有人可以告诉我该怎么做吗?谢谢

Vol*_*erK 17

array_rand()可以采用两个参数,即数组和要选择的(不同)元素的数量.

mixed array_rand(array $ input [,int $ num_req = 1])
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
  echo $my_array[$key];
}
Run Code Online (Sandbox Code Playgroud)


mid*_*dus 9

那这个呢?

$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.
Run Code Online (Sandbox Code Playgroud)

  • 对于非常大的数组,这可能会非常慢,尽管您当然不必仅仅为了获取两个元素而对整个数组进行洗牌。 (2认同)

phe*_*cks 6

您可以随时删除第一次选择的元素,然后再不会选择它.如果您不想修改数组,请创建副本.

 for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;

    unset($my_array[$random]);
 }
Run Code Online (Sandbox Code Playgroud)

  • 我使用循环是因为这意味着对 creativz 代码的更改最少。另外,它可以轻松扩展代码以选择任意数量的元素 (2认同)