sophie
sophie

Reputation: 1521

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,
)

Upvotes: -1

Views: 108

Answers (2)

mickmackusa
mickmackusa

Reputation: 48091

Save the first array as the initial data of the result array. Then loop over the second array and add the current value to either the pre-existing key's value or 0.

Code: (Demo)

$A = ["EUR" => 10, "USD" => 20];
$B = ["EUR" => 10, "JPY" => 20];

$result = $A;
foreach ($B as $k => $v) {
    $result[$k] = ($result[$k] ?? 0) + $v;
}
var_export($result);

Upvotes: 0

Jan-Henk
Jan-Henk

Reputation: 4874

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);

Upvotes: 2

Related Questions