phparrayssumassociative-arraymerging-data

Merge two flat associative arrays and sum the values of shared keys


I have two arrays :

$A = array("EUR" => 10, "USD" => 20)
$B = array("EUR" => 10, "JPY" => 20)

I want to merge and sum the the value which have the same keys.

$C = array(
    "EUR" => 20, // array(10, 10),
    "JPY" => 20,
    "USD" => 20,
)

Solution

  • With this code:

    <?php
    $A = array("EUR"=>10,"USD"=>20);
    $B = array("EUR"=>10,"JPY"=>20);
    
    $C = $A;
    foreach ($B as $key => $value) {
        if (isset($C[$key])) {
            $C[$key] = $C[$key] + $value;
        } else {
            $C[$key] = $value;
        }
    }
    

    the result will be the following array:

    array(3) {
      ["EUR"] => int(20)
      ["USD"] => int(20)
      ["JPY"] => int(20)
    }
    

    It already calculates the sum. For proof look at http://codepad.org/Aay0bEh9.

    If you do want the entry for EUR in the resulting array $C to be an array(10, 10) you can change the body of the foreach loop into the following code:

    if (! isset($C[$key])) {
        $C[$key] = array();
    }
    $C[$key][] = $value;
    

    EDIT:

    For my last remark and code sample, instead of changing the body of the foreach you can simply do the following:

    $C = array_merge_recursive($A, $B);