Php – calculating sum in objects

objectPHP

I am in need to do this thing:
I have an object like below, but i am in need to do the sum of the numbers of objects like object1_(anything), object2_(anything)

stdClass Object
(
    [object1_2012_06_12] => 16
    [object2_2012_06_12] => 10
    [object1_2012_06_11] => 16
    [object2_2012_06_11] => 10
)

For examaple: sum of object1_(anything) will be (object1_2012_06_12 + object1_2012_06_11) = (16+16)=32

Best Answer

You can cast your object to array:

$sum = 0;
foreach ((array)$myobj as $v) {
  $sum += intval($v);
}

Or as suggested by @MarkBaker:

$sum = array_sum((array)$myobj);