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)
1
  • Just a note, every answer here assumes all the values will be numberical. Keep that in mind. Commented May 21, 2015 at 7:09

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Please explain use of ${"array$x"}
@jQuery.PHP.Magento.com actually its a simple variable variables 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
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];
    }
}

Comments

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
    )
*/

Comments

-2

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

1 Comment

It doesnt add the values when 5 exists 2 times.

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.