PHP array_sum() Function (original) (raw)

Last Updated : 19 Sep, 2024

The array_sum() function in PHP is used to calculate the sum of values in an array. It works with both indexed and associative arrays and can handle arrays containing both integers and floats. If the array is empty, it returns 0.

number array_sum ( $array )

Syntax

number array_sum(array $array)

Parameter

Return Value:

**Examples:

Input : $a = array(12, 24, 36, 48); print_r(array_sum($a)); Output :120

Input : $a = array(); print_r(array_sum($a)); Output :0

In the first example the array calculates the sum of the elements of the array and returns it. In the second example the answer returned is **0 since the array is empty.

**Example 1: Sum of Numeric Array

PHP `

`

Output:

120

**Example 2: Empty Array

PHP `

`

Output:

0

**Example 3: Array with Floating Point Numbers

PHP `

1.42, "biotic" => 12.3, "charisma" => 73.4); // calculating sum print_r(array_sum($b)); ?>

`

Output:

87.12