23

I have an array of objects, and i want to sum value of one of the properties, 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?

6 Answers 6

46

array_reduce could be one way to do it; Just simply add your $array

$sum = array_reduce($array, function($carry, $item)
{
    return $carry + $item->commission;
});

var_dump($sum);
Sign up to request clarification or add additional context in comments.

1 Comment

is it necessary to use += operator in the callback? I guess it can be just +?
25

If you are using PHP 5.5

$arr_new = array_sum(array_column($yourarray, 'commission'));

2 Comments

The OP has an object, not array.
True, but this will work in a similar fashion if the object properties are public.
9

Let's say $arr stores your information. Implement the following function:

function sumProperties(array $arr, $property) {

    $sum = 0;

    foreach($arr as $object) {
        $sum += isset($object->{$property}) ? $object->{$property} : 0;
    }

    return $sum;
}

After that you just have to call sumProperties($array, 'commission').

Furthermore if you have more properties that could be summed, you could replace commission with those properties.

Comments

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

1 Comment

What happens if some of the objects in the array do not contain commission or the commission equals null?
1

The cleanest solution IMO is to use reduce:

$total = array_reduce( commissionsArray, function ($sum, $entry) {
  $sum += $entry->commission;
  return $sum;
}, 0);

You can check it out here:
https://wtools.io/php-sandbox/b4nG

However, if your array contains arrays instead of objects, you can use a readable code (it works for objects if your php versions is prior to 8.0.0, but it is not a very good practice to use implicit cast):

array_sum(array_column($commissionsArray, 'importe_final'));

You can chack it out here:
https://wtools.io/php-sandbox/b4nK

Comments

1

Maybe it's too late, but you can use this code (min version: PHP 7.4):

$sum = array_sum(array_map(fn($item)=>$item->commission, $arrayOfObjects));
//commission is a property of your object which has one of the number types

In this example, we map array of objects to array of numbers, and then we can calculate sum of the array with array_sum.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.