Ways of getting 20% of elements in array – PHP

  • A+
Category:Languages

I have an array of n elements and I need to get random 20% of those elements into another array. Is there any function which can achieve this?

Currently what I can think of is this:

foreach ($orders as $order) {     if (rand(1, 100) > 80) {         echo('20%');     } else {         echo('80%');     } } 

Is there a more optimal way?

 


You could shuffle the array and then take the first 20% elements.

$array = [1, 2, 3, 4]; shuffle($array);      $twenty = array_slice($array, 0, floor(count($array) / 5)); $eighty = array_slice($array, floor(count($array) / 5)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: