SIndhu
SIndhu

Reputation: 687

php mathematical addition of numerical values in 2 associative arrays

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

Upvotes: 0

Views: 413

Answers (3)

bharath
bharath

Reputation: 1233

you need

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

Upvotes: -2

Core Xii
Core Xii

Reputation: 6441

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

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

$resultArray = $array1;
foreach($array2 as $key => $value) {
   if (isset($resultArray[$key])) {
      $resultArray[$key] += $value;
   } else {
      $resultArray[$key] = $value;
   }
}

Upvotes: 2

Related Questions