I am looking for an array_merge()
function that does NOT replace values, but ADDS them.
Example, this is the code I am trying:
echo "<pre>";
$a1 = array(
"a" => 2
,"b" => 0
,"c" => 5
);
$a2 = array(
"a" => 3
,"b" => 9
,"c" => 7
,"d" => 10
);
$a3 = array_merge($a1, $a2);
print_r($a3);
Sadly, this outputs this:
Array
(
[a] => 3
[b] => 9
[c] => 7
[d] => 10
)
I then tried, instead of array_merge
, just simply adding the two arrays
$a3 = $a1 + $a2;
But this outputs
Array
(
[a] => 2
[b] => 0
[c] => 5
[d] => 10
)
What I truly want is to be able to pass as many arrays as needed, and then get their sum. So in my example, I want the output to be:
Array
(
[a] => 5
[b] => 9
[c] => 12
[d] => 10
)
Of course I can schlepp and build some function with many foreach
etc, but am looking or a smarter, cleaner solution.
array_merge
does merge two arrays while retaining all keys. But you want to sum the value of identical keys of two arrays, which is something else. – Epimenides