"100", "user2" => "200", "user3" => "300" ); How can I use array_sum to calculate the sum of the values excep" /> "100", "user2" => "200", "user3" => "300" ); How can I use array_sum to calculate the sum of the values excep" /> "100", "user2" => "200", "user3" => "300" ); How can I use array_sum to calculate the sum of the values excep"/>

Sum array values excluding value of element with specific key

2.8k Views Asked by At

If I have:

$my_array = array(
    "user1" => "100",
    "user2" => "200",
    "user3" => "300"
);

How can I use array_sum to calculate the sum of the values except the one of the user3?

I tried this function (array_filter), but it did not work:

function filterArray($value) {
    return ($value <> "user3");
}

I'm using PHP Version 5.2.17

3

There are 3 best solutions below

0
deceze On BEST ANSWER
array_sum(array_filter($my_array, 
                       function ($user) { return $user != 'user3'; },
                       ARRAY_FILTER_USE_KEY))

ARRAY_FILTER_USE_KEY became available in PHP 5.6.

Alternatively:

array_sum(array_diff_key($my_array, array_flip(array('user3'))))
0
IcedAnt On

A different approach:

foreach ($my_array as $key => $value) {
    if ($key !== "user3") {
        $sum += $value;
    }
}
echo $sum;
0
mickmackusa On

Rather than iterating the array multiple times with multiple functions or making iterated comparisons, perhaps just sum everything unconditionally and subtract the unwanted value.

If the unwanted element might not exist in the array then fallback to 0 via the null coalescing operator.

Code: (Demo)

echo array_sum($my_array) - ($my_array['user3'] ?? 0);
// 300

On the other hand, if it is safe to mutate your input array (because the data is in a confined scope or if you no longer need to the array in its original form), then unset() is a conditionless solution.

unset($my_array['user3']);
echo array_sum($my_array);