0

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?

user1547410
  • 863
  • 7
  • 27
  • 58
  • Possible duplicate of [multidimensional array array\_sum](http://stackoverflow.com/questions/12838729/multidimensional-array-array-sum) – JstnPwll Nov 17 '15 at 15:01
  • Unless this is really a bottleneck in your application do not optimize. See http://c2.com/cgi/wiki?PrematureOptimization – David Nov 17 '15 at 15:02
  • 1
    If you’re doing the loop anyway, then calculating the sum inside of it likely will perform better than doing it in a separate step afterwards. (And functions like `array_sum` need to loop over the elements as well, only “internally”.) – CBroe Nov 17 '15 at 15:05

3 Answers3

0

Where did $id come from?

the best would be $sum += $item->rowcount;

$sum = 0;
foreach ($items as $item) {
 $sum += $item->rowcount;
}
echo $sum;
Mindexperiment
  • 145
  • 1
  • 10
0

You can use array_reduce() like this

function sum($carry, $item){
    return $carry + $item['count'];
}
array_reduce($item_arr, "sum"); 
Artem Chernov
  • 856
  • 2
  • 8
  • 26
0

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;
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46