tags:

views:

48

answers:

4

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?

+1  A: 

You could use array_rand to pick the keys randomly and a foreach to gather the objects:

$objects = array();
foreach (array_rand($my_array, 8) as $key) {
    $objects[] = $my_array[$key];
}
Gumbo
Because it returns the array keys, not the values?
Chris B.
@Chris, that's why you use `$my_array[$key]`.
eyelidlessness
@Chris B.: I rephrased my answer. :)
Gumbo
@Gumbo: No points for pulling the trigger too soon, then correcting your answer after the fact. Credit goes to the guy who got it right the first time.
Chris B.
A: 

What about?:

$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
  $x = rand(0, $count);
  $my_array[$x];
}
jsumners
this won't work with associative arrays
Yorirou
+2  A: 
$result = array();
foreach( array_rand($my_array, 8) as $k ) {
  $result[] = $my_array[$k];
}
VolkerK
A: 
$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.

Enlightened