This Question have 3 answers right now.

PHP - Merge two associative arrays (add values if key exists)

Tags: php arrays

I have two associative arrays and they are very similar to each other (But not the same) they are both separate arrays and I want to merge them together while maintaining both the arrays this can be done by:

  • Making sure the values ADD if the keys already exist (I.e both the arrays contain the key 'dragon' and maybe the value is '30' on the first array and '26' on the second i want it to give me '56'
  • If these keys don't exist in the first array, just merge it normally.

I've tried using $tagItems = array_count_values($tagItems, $tagItems2); but this just gives me null when i try to json encode and echo it out.

I've also tried using $tagItems = array_merge($tagItems, $tagItems2); this adds the new keys but doesn't merge the duplicate keys values (just keeps merged array values).

The arrays in JSON format look something like this, one array is called $tagItems, the other is called $tagItems2

   "game1": 22,
   "game2": 20,
   "game3": 16,
   "game1": 22,
   "game2": 20,
   "game3": 16,
   "game4": 12,

What will allow me to do this?


This method using mapping and allows either array to have keys not present in the other array.

$merged = array_fill_keys(array_keys($a + $b), 0);
$sums = array_map(
    function($aVal, $bVal) { return $aVal + $bVal; },
    array_merge($merged, $a),
    array_merge($merged, $b)
$merged = array_combine(array_keys($merged), $sums);

Example Fiddle

At its shortest form where you want to merge $b into $a:

foreach ($b as $key => $value) {
    $a[$key] += $value;


However, it's best that you check if the array key exists before you write to it:

if (!array_key_exists($key, $a)) {
    $a[$key] = 0;
$a[$key] += $value;

You can use a WHERE clause for this. Convert your INSERT VALUES to an INSERT SELECT and add a WHERE clause.

For example,

INSERT INTO fields (field_name, control_type_id, needs_approval)
'Array Photos', 3, 0
WHERE Condition;

If Condition is true, it will insert the row. If Condition is false, the SELECT will return zero rows and thus the INSERT will insert zero rows.

Video about PHP - Merge two associative arrays (add values if key exists)