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;
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;
Use array_sum and array_slice function to sum the first two element
$sum = array_sum(array_slice($originalArray, 0, 2, true));
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;
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.