-6

I have two different arrays below:

Array ( [1] => 2 [2] => 3 [6] => 1 ) ; // array1 has 3 keys and 3 value 1=>2, 2=>3, 6=>1 
Array ( [1] => 2 [6] =>2 ) ;           // array2 has 2 keys and 2 value 1=>2, 6=>1 

I want to array1 and array2 which are the same key can SUM both value:

Ex: array1 "[1]=>2" and array2 "[1]=>2" want to out put like that [1]=>4; [6]=>3
Jess Stone
  • 677
  • 8
  • 21
Sher Ah
  • 19
  • 3
  • 1
    Did you search? http://stackoverflow.com/a/15549249/716691 – CodeBird Mar 06 '14 at 08:15
  • What should happen to the elements that do not have a similar key in the other array? – Peter Mar 06 '14 at 08:15
  • Well, what's stopping you from doing this? It's a trivial problem and easily solved with a `foreach()`. Are you just being lazy and expecting people to do your work for you? – Bojangles Mar 06 '14 at 08:16
  • This is it YUNOWORK. (Do you get it?) – Drixson Oseña Mar 06 '14 at 08:16
  • @CodeBird That's for summing indexed arrays, not associative arrays. – Barmar Mar 06 '14 at 08:16
  • 1
    @barmar if you look just under the answer I shared, you'll see the same solution as yours. I think people should search a bit, try stuff... Then if it doesn't work, come ask... As it looks the OP neither searched nor tried :) this is trivial. – CodeBird Mar 06 '14 at 08:24

2 Answers2

2
$result = array();
foreach ($array1 as $key => $value) {
    if (isset($array2[$key])) {
        $result[$key] = $value + $array2[$key];
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1
foreach($array1 as $key => $value) {
    if(array_key_exists($key, $array2)) {
        $array1[$key] += array2[$key];
    }
}
user3383116
  • 392
  • 1
  • 7