How to select a random value from an array in PHP?
P粉860897943
P粉860897943 2023-08-24 22:40:55
0
2
534

I have an array of objects in PHP. I need to randomly select 8 of them. My initial thought was to use array_rand(array_flip($my_array), 8), but this doesn't work because objects cannot be keys to arrays.

I know I could use shuffle, 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粉860897943
P粉860897943

reply all (2)
P粉364129744
$array = array(); shuffle($array); // 随机排列数组项的顺序 $newArray = array_slice($array, 0, 8);

Note that theshuffle()function passes arguments as references and changes them.

    P粉493313067
    $result = array(); foreach( array_rand($my_array, 8) as $k ) { $result[] = $my_array[$k]; }
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!