How to select random values ​​from an array in PHP?

I have an array of objects in PHP. I need to pick 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) , but this does not work because objects cannot act as keys for an array.

I know I can use shuffle , but I'm concerned about performance, as the array grows in size. Is this a better way, or is there a better way?

+4
source share
5 answers
 $result = array(); foreach( array_rand($my_array, 8) as $k ) { $result[] = $my_array[$k]; } 
+8
source
 $array = array(); shuffle($array); // randomize order of array items $newArray = array_slice($array, 0, 8); 

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

+5
source

You can use array_rand to randomly select keys and foreach to collect objects:

 $objects = array(); foreach (array_rand($my_array, 8) as $key) { $objects[] = $my_array[$key]; } 
+2
source

What??

 $count = count($my_array); for ($i = 0; $i < 8; $i++) { $x = rand(0, $count); $my_array[$x]; } 
0
source

I just found this in our code and was hoping to find a more readable solution:

 $rand = array_intersect_key($all, array_flip(array_rand($all, $count))); 
0
source

All Articles