What is the array_sum method in PHP?

The array_sum method returns the sum of the array.

Syntax

array_sum(array $array): int|float

Parameter

array: the array for which the sum is to be calculated.

The return type of this method is either an int or a float value. If the array is empty, then zero is returned.

Code

<?php
$arr = array(1,2,3);
echo "The array is \n";
print_r($arr);
echo "The sum is :";
echo array_sum($arr);
echo "\n-------\n";
$arr = array('a' => 1.4, 2);
echo "The array is \n";
print_r($arr);
echo "The sum is :";
echo array_sum($arr);
?>

In the code above:

  • We create an array with values 1,2,3 and call the array_sum method. This will return the sum of the array. In our case, it will return 6.
  • We then create another array with values 1.4, 2; for this array, array_sum will return 3.4 as a result.

In the array, the values that cannot be converted to numbers are skipped inside the array_sum method. For example:

<?php
$arr = array(1, "2", true, "yes", "no");
echo array_sum($arr);
?>

In the above code, we create an array with the values 1, "2", true, "yes", and "no".

In the above values:

  • "2" will be converted to 2.
  • true will be converted to 1.
  • "yes" & "no" will be skipped.

After converting, The sum will be calculated. In this case, the sum will be 4 (1 + 2 + 1).