Happy G Happy G - 7 months ago 11
PHP Question

Merge two arrays by adding their values

So I have two arrays and I want to merge them into one array by adding the values with the same key together.

array &a
Array
(
[0] => 4
[1] => 10
[2] => 3
[3] => 10
[4] => 7
)
array &b
Array
(
[0] =>
[1] => 1
[2] => 2
[3] => 2
[4] => 2

)


I expect the resulting array as

Array
(
[0] => 4
[1] => 11
[2] => 5
[3] => 12
[4] => 9

)

Answer

Use below code:-

$a = [4,10,3,10,7];
$b = ['',1,2,2,2];

$res = [];
foreach($a as $k=>$v){
   $res[] = $v + $b[$k]; 
}
echo '<pre>'; print_r($res);

output:-

Array
(
    [0] => 4
    [1] => 11
    [2] => 5
    [3] => 12
    [4] => 9
)

If second array $b has no similar numbers of record as first array $a then,

$a = [4,10,3,10,7];
$b = ['',1,2,2];  // removed last record

$res = [];
foreach($a as $k=>$v){
   $res[] = $v + (!empty($b[$k]) ? $b[$k] : 0); 
}
echo '<pre>'; print_r($res);

output:-

Array
(
    [0] => 4
    [1] => 11
    [2] => 5
    [3] => 12
    [4] => 7
)