Home  >  Q&A  >  body text

How to select a random value from an array in PHP?

<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>
P粉860897943P粉860897943442 days ago630

reply all(2)I'll reply

  • P粉364129744

    P粉3641297442023-08-25 21:11:22

    $array = array();
    shuffle($array); // 随机排列数组项的顺序
    $newArray = array_slice($array, 0, 8);

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

    reply
    0
  • P粉493313067

    P粉4933130672023-08-25 20:54:07

    $result = array();
    foreach( array_rand($my_array, 8) as $k ) {
      $result[] = $my_array[$k];
    }

    reply
    0
  • Cancelreply