2

for example

$array1 = array(item1=>5,item2=>7);
$array2 = array(item1=>5,item3=>7);

Actually i want to first check the array, if same key exist means value should be (arithmetically) added otherwise if not exists then it directly pushed to the array.

my output will be like

$nov-2014 =array(item1=>10,item2=>7,item3=>7)
Siguza
  • 21,155
  • 6
  • 52
  • 89
Indhiyan V
  • 31
  • 1
  • Just a note, every answer here assumes all the values will be numberical. Keep that in mind. – Kishor May 21 '15 at 07:09

4 Answers4

3

You can just plainly use a simple for and a foreach for that purpose. Of course create the final container. Initialize values, then just continually add thru keys:

$array1 = array('item1'=>5,'item2'=>7);
$array2 = array('item1'=>5,'item3'=>7);

$result = array();
for($x = 1; $x <= 2; $x++) {
    foreach(${"array$x"} as $key => $values) {
        if(!isset($result[$key])) $result[$key] = 0; // initialize
        $result[$key] += $values; // add
    }
}

print_r($result);

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
  • 1
    Please explain use of `${"array$x"}` – Pratik Joshi May 21 '15 at 07:09
  • 1
    @jQuery.PHP.Magento.com actually its a simple [variable variables](http://php.net/manual/en/language.variables.variable.php) concept, it basically iterates arrays `$array1` and `$array2`, oh i wish those arrays weren't separate, it could have been much easier, but anyway, i'l just have to work on what the OP got above there – Kevin May 21 '15 at 07:10
3

Try this:

$array1 = array(
    'item1' => 5,
    'item2' => 7
);
$array2 = array(
    'item1' => 5,
    'item3' => 7
);
$array_new = $array2;
foreach ($array1 as $key => $value) {
    if (!in_array($key, $array2)) {
        $array_new[$key] = $value + $array2[$key];
    }
}
Serge
  • 417
  • 2
  • 12
2

I think there is no built PHP function, use foreach.

$array1 = array('item1' => 5, 'item2' => 7);
$array2 = array('item1' => 5, 'item3' => 7);
$result = $array1;

foreach ($array2 as $key => $val) {
    if (isset($result[$key])) {
        $result[$key] += $val;
    } else {
        $result[$key] = $val;
    }
}

/*
    Output:
    Array
    (
        [item1] => 10
        [item2] => 7
        [item3] => 7
    )
*/
pavel
  • 26,538
  • 10
  • 45
  • 61
-2

Try array_merge. For associative arrays, this will keep same keys

qrazi
  • 1,406
  • 1
  • 15
  • 18