phparraysarray-filterphp-5.2array-sum

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


Solution

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