-2

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!

Vajira Lasantha
  • 2,435
  • 3
  • 23
  • 39
  • possible duplicate of [PHP Array Merge two Arrays on same key](http://stackoverflow.com/questions/14842272/php-array-merge-two-arrays-on-same-key) – Bruce Jun 15 '15 at 11:10

4 Answers4

1
$c = array();
foreach ($a as $k => $v) {
    if (isset($b[$k])) {
        $c[$k] = $b[$k] + $v;
    }
}

You need to check whether keys exist in both arrays.

marian0
  • 3,336
  • 3
  • 27
  • 37
1

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;
  }
}
Tommy Jinks
  • 747
  • 6
  • 21
1

You can easily do this by foreach loop, please see the example below

$c = array();
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
foreach ($a as $key => $value) {
    $tmp_value = $a[$key] + $b[$key];
    $c[$key] = $tmp_value;
}
print_r($c);
Faiz Rasool
  • 1,379
  • 1
  • 12
  • 20
  • Why should the OP "try this"? Please add an explanation of what you did and why you did it that way, not only for the OP but for future visitors to SO. – Jay Blanchard Jun 15 '15 at 14:53
1

You can simply use foreach as

foreach($b as $key => $value){
    if(in_array($key,array_keys($a)))
        $result[$key] = $a[$key]+$value;

}
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54