Reputation: 315
$arr1 = array('apple' => 1, 'mango'=>5, 'banana'=>3 );
$arr2 = array('apple' => 3, 'banana'=>2 );
my result array should be
array('apple'=>4, 'mango'=>5,'banana'=>5);
How can i do that?
Upvotes: 1
Views: 128
Reputation: 4318
If you really want a pretty one-liner then this would do for the present problem
array_walk($arr1, create_function('&$item,$key,$arr2', '$item += $arr2[$key] ;'),$arr2);
This uses the PHP trick of $array['non-existing-key'] evaluating to zero. However in real life I would have written this as
function walk(&$item,$key,$arr2) {
$item = array_key_exists($key,$arr2) ? $item + $arr2[$key] : $item;
}
array_walk($arr1,'walk',$arr2);
Upvotes: 0
Reputation: 454930
You can do:
foreach($arr2 as $key=>$val) {
if(isset($arr1[$key])) {
$arr1[$key] += $val;
} else {
$arr1[$key] = $val;
}
}
Upvotes: 7