0

Probably a simple one for you :

I have 2 arrays

$array1 = array(
  'foo' => 5,
  'bar' => 10,
  'baz' => 6
);

$array2 = array(
  'x' => 100,
  'y' => 200,
  'baz' => 30
);

I wish to get a third array by combining both the above, which should be :

$result_array = array(
  'foo' => 5,
  'bar' => 10,
  'baz' => 36,
  'x' => 100,
  'y' => 200,
);

Is there any built in 'array - way' to do this, or will I have to write my own function ? Thanks

3 Answers 3

2
$resultArray = $array1;
foreach($array2 as $key => $value) {
   if (isset($resultArray[$key])) {
      $resultArray[$key] += $value;
   } else {
      $resultArray[$key] = $value;
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that works. How come there's no built in way for this i wonder. by the way, I havent negative voted any of the answers on this page ! i cant - vote anyways ;p
Probably because you want to add the matching values, others might want to subtract, others to do a logical and, etc... so you'd need a function for every possible operation. And it isn't exactly difficult to write your own, just a few short lines of code
1

There's no built-in function for this, you'll have to write your own.

1 Comment

Not sure why this got downvoted; it explicitly and specifically answered the question: "Is there a function, or do I have to make my own?"
-2

you need

$newArray = $array1;
foreach($array2 as $key => $value) {
    if(array_key_exists($key, $newArray)){
     $newArray[$key] += $value;
    }else{
     $newArray[$key] = $value;
    }
}

2 Comments

OP is requesting that the values be added when the keys match
sorry, that ate up 6 from baz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.