fightstarr20
fightstarr20

Reputation: 12608

PHP - Calculate percentage of items in array

I have the following array

Array
(
[0] => Array
    (
        [rate] => normal-rate
        [quantity] => 1
    )

[1] => Array
    (
        [rate] => extra-rate
        [quantity] => 2
    )

[2] => Array
    (
        [rate] => extra-rate
        [quantity] => 1
    )

)

I am trying to work out the percentage of extra-rate items there are in the array, can I do this directly or should I first create a new array by counting the quantity and adding everything together?

Upvotes: 0

Views: 505

Answers (1)

u_mulder
u_mulder

Reputation: 54841

In a one liner it is:

$pers = count(array_filter($array, function($v) { return $v['rate'] == 'extra-rate'; })) / count($array);

In a simple foreach it is:

$count = 0;
foreach ($array as $v) {
    if ($v['rate'] == 'extra-rate') {
        $count++;
    }
}
$pers = $count / count($array);

Considering quantity:

$ex_qty = 0;
$total_qty = 0;
foreach ($array as $v) {
    if ($v['rate'] == 'extra-rate') {
        $ex_qty += $v['quantity'];
    }
    $total_qty += $v['quantity'];
}
$pers = $ex_qty / $total_qty;

Upvotes: 3

Related Questions