简体   繁体   中英

Sum array values excluding value of element with specific key

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

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

A different approach:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM