php -Merging an Array

Posted by Vidhu Shresth Bhatnagar on Stack Overflow See other posts from Stack Overflow or by Vidhu Shresth Bhatnagar
Published on 2012-12-12T22:49:24Z Indexed on 2012/12/12 23:03 UTC
Read the original article Hit count: 434

Filed under:
|
|
|

I have two array which i want to merge in a specific way in php. So i need your help in helping me with it as i tried and failed.

So say i have two arrays:

$array1= array(
    "foo"        => 3,
    "bar"        => 2,
    "random1"    => 4,
);

$array2= array(
    "random2"    => 3,
    "random3"    => 4,
    "foo"        => 6,
);

Now when during merging i would like the common key's values to be added. So like foo exists in array1 and in array2 so when merging array1 with array 2 i should get "foo" => "9"

I better illustration would be the final array which looks like this:

$array1= array(
    "foo"        => 9,
    "bar"        => 2,
    "random1"    => 4,
    "random2"    => 3,
    "random3"    => 4,
);

So again i would like the values of the common keys to be added together and non common keys to be added to array or a new array

I hope i was clear enough

Thanks, Vidhu

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays