How to select a random value from an array in PHP?
P粉860897943
P粉860897943 2023-08-24 22:40:55
0
2
632
<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粉860897943
P粉860897943

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

Note that the shuffle() 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!