-2

I have two arrays.

$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);

I want to merge these two arrays and get following result.

$c = array('a' => 5, 'b' => 12, 'c' => 18);

What is the easiest way to archive this?

Thanks!

1

4 Answers 4

1

As mentioned in the comments, looping through the array will do the trick.

$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
$c = array();
foreach($a as $index => $item) {
  if(isset($b[$index])) {
    $new_value = $a[$index] + $b[$index];
    $c[$index] = $new_value;
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

What if the keys were not same
@uchiha Good point. But both my arrays contains last 30 days as keys.
Its just a question you need a rigid output
@Uchiha Great point. I've added an isset to solve this. This will merely ignore any other keys that are in $a but not in $b. This could get more complex by adding the new key to $c, however this doesn't fit the scenario of the question so I didn't add it.
@Uchiha Missed a bracket. I shall blame this on it being a Monday morning!
|
1
$c = array();
foreach ($a as $k => $v) {
    if (isset($b[$k])) {
        $c[$k] = $b[$k] + $v;
    }
}

You need to check whether keys exist in both arrays.

Comments

1

You can simply use foreach as

foreach($b as $key => $value){
    if(in_array($key,array_keys($a)))
        $result[$key] = $a[$key]+$value;

}

Comments

1

You can easily do this by foreach loop, please see the example below

$c = array();
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
foreach ($a as $key => $value) {
    $tmp_value = $a[$key] + $b[$key];
    $c[$key] = $tmp_value;
}
print_r($c);

1 Comment

Why should the OP "try this"? Please add an explanation of what you did and why you did it that way, not only for the OP but for future visitors to SO.

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.