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,
)
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,
)
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);
With this code:
the result will be the following array:
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:
EDIT:
For my last remark and code sample, instead of changing the body of the foreach you can simply do the following: