1
$arrOne = array(
    '49' => 5
);

$arrTwo = array(
    '49' => 5
);

$myArray = array($arrOne, $arrTwo);
$sumArray = array();

foreach ($myArray as $k => $subArray) {
    foreach ($subArray as $id => $value) {
        $sumArray[$id] += $value;
    }
}

print_r($sumArray);

Result

error: Notice: Undefined offset: 49 in

how to fix it?

I want result is: array(49 => 10)

5
  • @Anant Looks like error messages are disabled there - compare to 3v4l. Commented Jul 1, 2016 at 7:41
  • a += b is somewhat equivalent to a = a + b. That means you're doing $sumArray[$id] = $sumArray[$id] + $value, when $sumArray[$id] obviously doesn't exist. Commented Jul 1, 2016 at 7:42
  • @Siguza oh i got the point Commented Jul 1, 2016 at 7:43
  • haitruonginfotech please check the answers below and mark+up-vote one as a correct answer. you can up-vote too if they are useful too. thanks. Commented Jul 1, 2016 at 23:06
  • People are not responding. deleting my answer Commented Jul 3, 2016 at 4:47

2 Answers 2

2

Because it's not defined yet, and you want to add (+=) to an undefined offset. Change the inner code to below:

if (!isset($sumArray[$id])) {
    $sumArray[$id] = $value;
} else {
    $sumArray[$id] += $value;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@deceze, thanks for formatting as code. Somehow it kept giving error.
1

Just initialise the index if it doesn't exist yet.

if(!isset($sumArray[$id])) {
    $sumArray[$id] = 0;
}

Patched into your code:

$arrOne = array(
    '49' => 5
);

$arrTwo = array(
    '49' => 5
);

$myArray = array($arrOne, $arrTwo);
$sumArray = array();

foreach ($myArray as $k => $subArray) {
    foreach ($subArray as $id => $value) {
        if(!isset($sumArray[$id])) {
            $sumArray[$id] = 0;
        }
        $sumArray[$id] += $value;
    }
}

print_r($sumArray);

[ Demo ]

Comments

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.