Search code examples
phparrayssumarray-merge

Merge two arrays and sum values where keys match


How do I combine these two arrays, so that the keys stay the same, but the values are arithmetically determined?

Note - the keys might not always line up in each array, per my example:

$Array1 = [4 => 100, 5 => 200, 6 => 100, 7 => 400];
$Array2 = [2 => 300, 5 => -100, 16 => -500];

Desired output:

$Array3 = [2 => 300, 4 => 100, 5 => 100, 6 => 100, 7 => 400, 16 => -500];

Solution

  • You can use array_map for this:

    $Array3 = array_map(function($a,$b) {return $a+$b;},$Array1,$Array2);
    

    However this will only work if you have the same keys in both arrays (which, in your example, you don't).

    If this is an issue, the easiest workaround would probably be:

    $allKeys = array_merge(array_keys($Array1),array_keys($Array2));
    $Array3 = Array();
    foreach($allKeys as $k) {
        $Array3[$k] = (isset($Array1[$k]) ? $Array1[$k] : 0)
                     +(isset($Array2[$k]) ? $Array2[$k] : 0);
    }
    

    EDIT Just realised the above code is not optimal. Rewriting:

    $allKeys = array_unique(array_merge(array_keys($Array1),array_keys($Array2)));
    // rest of code as above
    

    Actually not sure if the overhead of repeated keys is more or less than the overhead of checking uniqueness...