PHP array_​sum() Function

What is PHP array_sum() Function?

If you want to know sum of all the values of an array, use array_sum() function.

Syntax:

array_sum(array);

Parameters:

The Function 1 parameter which is required-

array (Required): It specifies the input array.

Return Values:

The function returns-

  • An integer if all the values are integer.
  • A float if at least one value is float.
  • Zero if the array is empty.

Examples:

Example 1:

<?php
$numbers = [1, 2, 3, 4];
$sum = array_sum($numbers);
echo "The sum of all the values in the array is: " . $sum;
?>

Output:

The sum of all the values in the array is: 10

Example 2:

<?php
$numbers = [1.5, 2, 3, 4];
$sum = array_sum($numbers);
echo "The sum of all the values in the array is: " . $sum;
?>

Output:

The sum of all the values in the array is: 10.5

Example 3:

<?php
$numbers = [];
$sum = array_sum($numbers);
echo "The sum of all the values in the array is: " . $sum;
?>

Output:

The sum of all the values in the array is: 0

Example 4:

<?php
$numbers = [1, 2, 3, 4,"version"];
$sum = array_sum($numbers);
echo "The sum of all the values in the array is:" . $sum;
?>

Output:

The sum of all the values in the array is: 10

Notes on array_sum() Function:

  • If one value if string, the function considers it as zero (0). Check example 4.
  • It works on both indexed and associative arrays.

PHP Version Support:

PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8

Summary: PHP array_sum() Function

The array_sum() function is a built-in PHP function and part of the PHP’s array functions. It is an easy way to sum all the numeric values of an array.

Reference:

https://www.php.net/manual/en/function.array-sum.php