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

$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.

Leave a Comment