Home >Backend Development >PHP Tutorial >How to Merge Associative Arrays with Summed Values for Shared Keys?
Merge Associative Arrays with Summed Values for Shared Keys
Merging multiple associative arrays while combining values for shared keys can be a common yet challenging task. This article presents several solutions to address this issue.
Array Merge with Summation
The goal is to merge two or more flat associative arrays (arrays with string keys and non-array values) and sum the values associated with identical keys. This differs from the default behavior of array_merge() function which replaces values for duplicate keys.
Examples
Consider the following example:
<code class="php">$a1 = array("a" => 2, "b" => 0, "c" => 5); $a2 = array("a" => 3, "b" => 9, "c" => 7, "d" => 10);</code>
If we were to use array_merge() to combine these arrays, the result would be:
<code class="php">$a3 = array_merge($a1, $a2); print_r($a3); </code>
Output:
Array ( [a] => 3 [b] => 9 [c] => 7 [d] => 10 )
As you can see, the values for shared keys ("a", "b", "c") are not summed but replaced.
Custom Solutions
To achieve the desired result, we can utilize a custom function that iterates over the keys of the combined arrays and sums the values for shared keys. Here's one such implementation:
<code class="php">$sums = array(); foreach (array_keys($a1 + $a2) as $key) { $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0); }</code>
Output:
<code class="php">Array ( [a] => 5 [b] => 9 [c] => 12 [d] => 10 )</code>
This function allows us to merge multiple arrays with shared keys and provides the summed values for those keys.
The above is the detailed content of How to Merge Associative Arrays with Summed Values for Shared Keys?. For more information, please follow other related articles on the PHP Chinese website!