0

I got problem with array when i want make addition of 2 first number. What I doing wrong ?

$items = array('b' => 10,'a' => 10, 31, 51));

$sum = 0;
foreach ($items as $value) {
    $sum = $item['a'] + $item['b'];
}
echo $sum;
1
  • For each loop is not required at all to sum the first 2 elements. Commented Sep 7, 2018 at 6:09

5 Answers 5

1

Use array_sum and array_slice function to sum the first two element

$sum = array_sum(array_slice($originalArray, 0, 2, true));
Sign up to request clarification or add additional context in comments.

Comments

1

simple write below and its work

$items = array('b' => 10,'a' => 10, 31, 51);
$sum = $items['b'] + $items['a'];
echo $sum;

Comments

0

There is some syntax erros in your code i.e. you have defined $items as array and you are using $item, also some extra brackets. I have just modified your code, see below

$items = array('a' => 10,'b' => 30, 'c' =>31, 'd' =>51);

$sum = 0;
foreach ($items as $value) {
    $sum = $items['a'] + $items['b'];
}
echo $sum;

2 Comments

I think for each loop is not required at all to sum the first 2 elements.
Yes, it is not required, but @Mati Urbaniak logic is also working using foreach
0

just use addition instead of executing a loop.

$sum = $items['a'] + $items['b'];

Comments

0

You don't need to use any loop.

Just sum the array items based on the key.

$sum = $items['b'] + $items['a'];

You might need to use array_key_exists to avoid the exception if the key is not available. I would do it like this

$sum = (array_key_exists('a',$items['a'])?$items['a']:0) +
       (array_key_exists('b',$items['b'])?$items['b']:0);

If key exists, use the value else add 0.

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.