Vajira Lasantha Vajira Lasantha - 2 months ago 12
PHP Question

PHP Merge (Add) Two Arrays by Same Key

I have two arrays.

$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);


I want to merge these two arrays and get following result.

$c = array('a' => 5, 'b' => 12, 'c' => 18);


What is the easiest way to archive this?

Thanks!

Answer

As mentioned in the comments, looping through the array will do the trick.

$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
$c = array();
foreach($a as $index => $item) {
  if(isset($b[$index])) {
    $new_value = $a[$index] + $b[$index];
    $c[$index] = $new_value;
  }
}
Comments