In PHP, Sum The Value Of An Array.

In this article, we will learn how to find the sum of the values in an array using PHP. We will use the PHP array sum() function, a built-in function that gives the sum of all the array elements.

PHP array_sum() function

The array sum() function in PHP calculates and returns the total value of an array.

PHP's array sum() function can calculate the total value of both indexed and associative arrays.


The following example will calculate the total values contained in an indexed array.

<?php
$array=array(122,395,856,499,716);
$sum=array_sum($array);
echo $sum;
?>


Output

2588


The second example will calculate the total values included in the associative array.

<?php
$array=array("a"=>10,"b"=>50,"c"=>100);
$sum=array_sum($array);
echo $sum;
?>


Output

160


The total of the array containing fractional values.

<?php
$array=array("a"=>90.6,"b"=>40.3,"c"=>60.2);
$sum=array_sum($array);
echo $sum;
?>


Output

191.1