The array_sum() function calculates a sum of values in an array.
PHP array_sum
The array_sum() is a built-in PHP function that returns the sum of all the values in the array. It takes an array parameter and returns the sum of all its values. It returns the 0 if the array is empty. The returned sum may be integer or float.
Syntax
See the following syntax.
array_sum($array)
Parameters
Now, see the following code example.
<?php // app.php $arr = [19, 21, 46]; echo array_sum($arr);
See the following output.
If you want to find an AVERAGE of the values in your array, use the sum and count the functions together. For example, let’s say your array is $arr, and you want the average.
<?php // app.php $arr = [19, 21, 46]; $average = array_sum($arr) / count($arr); echo $average;
See the below output.
So, we can calculate the sum of values in an array using the array_sum() function.
Passing an empty array
Let’s see the example where the array is empty.
<?php // app.php $arr = []; echo array_sum($arr);
See the output.
Integers and String Values in array_sum()
If you pass the array containing both the strings and integers. Then the PHP array_sum() Function returns a sum of integers. The strings are considered as 0.
<?php // app.php $arr = ['krunal', 21, 'ankit', 19]; echo array_sum($arr);
See the following output.
If you want to check if there are only strings in the array, you can use the combination array_sum and array_map() as the following code.
<?php // app.php function check_only_strings_in_array($arr) { return array_sum(array_map('is_string', $arr)) == count($arr); } $arr1 = array('1', 2); $arr2 = array(1, 2, []); $arr3 = array('krunal', 'ankit'); var_dump( check_only_strings_in_array($arr1), check_only_strings_in_array($arr2), check_only_strings_in_array($arr3) ); ?>
That’s it for this tutorial.