So i have an array which is created like this via a loop
foreach ($items as $item)
{
$item_arr[$id]['count'] = $item->rowcount;
}
Now what i want to do is get the sum of the counts. I know i can just use $sum += $item->rowcount; but i was wondering if there was a more efficient way using something like this outside the loop when the foreach is done:
$sum = array_sum($item_arr[]['count']);
But that doesn't work says it doesn't like [], is there a way to do it or is the best way just to keep count in the foreach loop. Just would like to keep the code cleaner and more readable but maybe its a stupid question?
Where did $id come from?
the best would be $sum += $item->rowcount;
$sum = 0;
foreach ($items as $item) {
$sum += $item->rowcount;
}
echo $sum;
You can use array_reduce() like this
function sum($carry, $item){
return $carry + $item['count'];
}
array_reduce($item_arr, "sum");
A variation of a theme perhaps but like array_reduce
you could alternatively use array_walk
$total=0;
$arr=array(
array('count'=>23),
array('count'=>54),
array('count'=>91),
array('count'=>86)
);
array_walk( $arr, function( &$i, $k, &$t ){
$t += $i['count'];
}, &$total );
echo 'total:'.$total;