0

How would i get the sum of the totals for the following PHP Array?

I am running this: print_r($myArray);

Array
(
    [0] => Array
        (
            [total] => 100.0000
        )

    [1] => Array
        (
            [total] => 100.0000
        )

    [2] => Array
        (
            [total] => 689.5000
        )
)
3
  • Have you tried looping over the list, then summing the entries up by using a variable? Commented Oct 19, 2012 at 1:20
  • possible duplicate of How to sum up values inside a variable? Commented Oct 19, 2012 at 1:22
  • have you tried any code so far? Commented Oct 19, 2012 at 1:25

1 Answer 1

3

You can use array_reduce

$total = array_reduce($array, function($a,$b) {return $a + $b['total'];});
var_dump($total);

You can use array_map

$total = 0;
array_map(function($v) use(&$total) { $total += $v['total'];},$array);
var_dump($total);

Your Just loop

for($i = 0, $total = 0; $i < count($array); $i ++) {
    $total += $array[$i]['total'];
}
var_dump($total);

Output

float 889.5
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that is great! I also had to use floatval($total) to convert it from string to float.

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.