sam
sam

Reputation: 315

How to combine 2 arrays based on indexes in PHP?

$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

Answers (2)

rjha94
rjha94

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

codaddict
codaddict

Reputation: 454930

You can do:

foreach($arr2 as $key=>$val) {
        if(isset($arr1[$key])) {
                $arr1[$key] += $val;
        } else {
                $arr1[$key] = $val;
        }   
}

http://www.ideone.com/rDFFW

Upvotes: 7

Related Questions