0

I want to add data of two Key=>Value pair array for matching keys.

I have these two arrays

$array1=array(
              'a'=>1, 
              'b'=>2, 
              'c'=>3, 
              'd'=>4
             );
$array2=array(
              'c'=>3, 
              'd'=>4
             );

I am using array_merge_recursive to merge these arrays like this

$array_merge=array_merge_recursive($array1,$array2);    
print_r($array_merge);

But it doesn't add two arrays it gives result like

       Array ( 
              [a] => 1 
              [b] => 2 
              [c] => 3 
              [d] => 4 
             ) 

Is it possible to get result like

       Array ( 
              [a] => 1 
              [b] => 2 
              [c] => 6
              [d] => 8
             ) 

Please see and suggest any possible way to do this.

Thanks

  • Why would you expect a merge function to add the numbers together? – Barmar Aug 22 '16 at 09:27
  • Loop through the first array, for each item check if the key exists in the second array, if so: add the value to the item of the first array – Bert Aug 22 '16 at 09:28
  • @Barmar I googled about adding arrays and this is what I found –  Aug 22 '16 at 09:28
  • 1
    `$array_merge= array_merge_recursive($array1, $array2); array_walk($array_merge, function(&$value) { if (is_array($value)) $value = array_sum($value); });` [Demo](https://3v4l.org/ntr7P) – Mark Baker Aug 22 '16 at 09:32
  • @MarkBaker Thanks it works, Also will be good to this for 250+ keys –  Aug 22 '16 at 09:36

0 Answers0