1

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Sara Z
  • 625
  • 7
  • 18

3 Answers3

3
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'))))
deceze
  • 510,633
  • 85
  • 743
  • 889
1

A different approach:

foreach ($my_array as $key => $value) {
    if ($key !== "user3") {
        $sum += $value;
    }
}
echo $sum;
IcedAnt
  • 444
  • 3
  • 12
0

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);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136