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?
What about?:
I just found this in our code and was hoping to find a more readable solution:
You can get multiple random elements from an array with this function:
You could use
array_rand
to pick the keys randomly and aforeach
to gather the objects:Notice that
shuffle()
function gives parameter as a reference and makes the changes on it.