We can store values in an array and calculate the sum of
the values inside the array by using the array_sum function. This function will
add all the values of the array. We will create an array with some integer value
and then find out the sum.
$value= array(2,5,6,8,9);
echo "Sum of vlues = ".array_sum($value)."<br>";
Sum of all elements of an Array
We can store float value in an array and get the sum of
them by using the array_sum command. Here is one example.
The output of the above line would be 9.3 ( the sum of all values inside the array)
Array with string and number as elements
We can apply array_sum() function to an array with both number and string as elements. The string part will be ignored and the sum of numbers will be returned. The original array remains unchanged.
Here is the code.
<?Php
$value= array(2,5,6,'plus2net',8,9);
echo "Sum of values = ".array_sum($value)."<br>";
?>
Output is here
Sum of values = 30
Sum with keys
$input=array('One' =>1,'Two'=>2,'Three'=>3,'Fourth');
echo array_sum($input); // Output is 6
Output is
6
Average value of all elements of the array
We already know how to find out total number of elements present inside array by using count() function. By using count() and array_sum() we will find out the average value of the elements of the array.