PHP Merge (Add) Two Arrays by Same Key

166 views Asked by At

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!

4

There are 4 answers

6
Tommy Jinks On BEST 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;
  }
}
0
marian0 On
$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.

1
Faiz Rasool On

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);
0
Narendrasingh Sisodia On

You can simply use foreach as

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

}