tags:

views:

79

answers:

4

Is there a simple way to get the total of all items in a PHP array?

Also, how can I output the contents of an array for debugging purposes?

+11  A: 

What you are looking for is array_sum http://uk.php.net/manual/en/function.array-sum.php

array_sum — Calculate the sum of values in an array

To output the contents of an array use var_dump or print_r. e.g

$myarr = array(1,5,2,7,6);

echo "<pre>";
print_r($myarr);
echo "</pre>";

echo "The Sum of my array is ".array_sum($myarr);

// Output

Array
(
    [0] => 1
    [1] => 5
    [2] => 2
    [3] => 7
    [4] => 6
)

The Sum of my array is 21
Lizard
Or use var_dump() instead of print_r()
powtac
I had that in my answer already "use var_dump or print_r" :p
Lizard
+2  A: 

http://php.net/array%5Fsum

PHP has a great documentation site, be sure to reference it.

Matt
PHP has a *ton* of array-specific (and string-specific) functions, and it's a good idea to read over the options on php.net any time you're trying to do something funky with either of them.
John Fiala
A: 

if you just need it for debugging var_dump($variable); is good for seeing what everything's doing.

andy-score
A: 

I'm not sure whether you mean the total number of items or the total of all items (in the case of numeric values)...

  • To get the number of items in an array use count()
  • To get the sum of all numbers use array_sum()

count array_sum

Alex