How to select a random value from an array in PHP?
P粉860897943
2023-08-24 22:40:55
<p>I have an array of objects in PHP. I need to randomly select 8 of them. My initial thought was to use <code>array_rand(array_flip($my_array), 8)</code>, but this doesn't work because objects cannot be keys to arrays. </p>
<p>I know I could use <code>shuffle</code>, but I'm worried about performance getting worse as the array grows. Is this the best way, or is there a more efficient way? </p>
Note that the
shuffle()
function passes arguments as references and changes them.