Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select random values from an array in PHP?

Tags:

arrays

php

random

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.

I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?

like image 467
Chris B. Avatar asked Sep 03 '10 19:09

Chris B.


2 Answers

$result = array();
foreach( array_rand($my_array, 8) as $k ) {
  $result[] = $my_array[$k];
}
like image 94
VolkerK Avatar answered Sep 28 '22 01:09

VolkerK


$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);

Notice that shuffle() function gives parameter as a reference and makes the changes on it.

like image 44
Enlightened Avatar answered Sep 28 '22 01:09

Enlightened