Reputation: 1178
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?
Upvotes: 2
Views: 473
Reputation: 26153
To get two arrays by one function call, use array_splice function. After
shuffle($array);
$twenty = array_splice($array, floor(count($array) / 5 * 4));
$twenty will held 1/5 of source array and $array - other items
Upvotes: 2
Reputation: 144
Shuffle is the simplest solution for this case
$array = [1,2,3,4]
shuffle($array);
$firstSlice = array_slice($array , 0 , count($array)/2);
$secondSlice = array_slice($array , count($array)/2 , count($array));
Upvotes: 0