Efficiently pick n random elements from PHP array (without shuffle)

前端 未结 5 2038
独厮守ぢ
独厮守ぢ 2020-11-29 12:05

I have the following code to pick $n elements from an array $array in PHP:

shuffle($array);
$result = array_splice($array, 0, $n);
         


        
5条回答
  •  天命终不由人
    2020-11-29 13:07

    $randomArray = [];
    while (count($randomArray) < 5) {
      $randomKey = mt_rand(0, count($array)-1);
      $randomArray[$randomKey] = $array[$randomKey];
    }
    

    This will provide exactly 5 elements with no duplicates and very quickly. The keys will be preserved.

    Note: You'd have to make sure $array had 5 or more elements or add some sort of check to prevent an endless loop.

提交回复
热议问题