user2706762 user2706762 - 3 months ago 8
PHP Question

suming objects property in array

I have an array of objects, and i want to sum value of one of the property, example:

Array
(
[0] => stdClass Object
(
[name] => jon
[commission] => 5

)
[1] => stdClass Object
(
[name] => smith
[commission] => 1

)
[2] => stdClass Object
(
[name] => philip
[commission] => 8

)
)


I want to sum all the commissions in the array, result should be 14.

what is a good way for this?

thanks

Answer
$sum = 0;
foreach($arrObj as $key=>$value){
  if(isset($value->commission))
     $sum += $value->commission;
}
echo $sum;