The50
The50

Reputation: 1178

Ways of getting 20% of elements in array - PHP

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

Answers (4)

splash58
splash58

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

Mohammed Salah
Mohammed Salah

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

Nick
Nick

Reputation: 147206

The simplest solution is probably to use shuffle:

shuffle($orders);
for ($i = 0; $i < count($orders) / 5; $i++) {
    // do something with the first 20% of elements
}
for (; $i < count($orders); $i++) {
    // do something with the rest of the array
}

Upvotes: 2

Jerodev
Jerodev

Reputation: 33196

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));

Upvotes: 8

Related Questions