Search code examples
phparrayssum

How to sum the values of an array?


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?


Solution

  • 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