Search code examples
phparrayssummappinggrouping

Calculate sum of mapped values for each unique value in a flat array


I have a loop where I push values into two arrays simultaneously, so I get two arrays like this:

$array1 = [1, 1, 1, 2, 2, 3];
$array2 = [2, 4, 5, 2, 1, 5];

How can I get the sum for each unique number of $array1, meaning 1,2,3, for the corresponding keys of that number from $array2.

Example; for the value 1 of the $array1 we got the keys 0, 1, 2. Now I want to sum up the values from $array2 which have those keys, resulting in 2 + 4 + 5 = 11.

Would I write a loop to get all the indexes that have 1 in $array1 and then get all the values from $array2 with those indexes and so on?

Desired output:

[1 => 11, 2 => 3, 3 => 5]

Solution

  • You can use array_map passing to function the two arrays and using a reference to an empty array with each total:

    $total = array_fill_keys( array_unique($array1), 0 );
    
    array_map
    (
        function( $a, $b ) use( &$total )
        {
            $total[$a] += $b;
        },
        $array1,
        $array2
    );
    
    print_r( $total );
    

    Output:

    Array
    (
        [1] => 11
        [2] => 3
        [3] => 5
    )
    

    eval.in demo

    array_map accepts more than one array, and pass its each item synchronized, so you can sum each $array2 value to $total element with same key as $array1 value.

    Note that we init $total with array_fill_keys only to avoid notices on creating new $total elements.