PHP array_sum() function
The array_sum()
function in PHP is used to calculate the sum of all values in an array. It is particularly useful when you need to quickly compute the total of numerical values stored in an array.
Syntax:
Parameters:
- $array: An array of numbers (integers or floats). The function will ignore any non-numeric values.
Return Value:
- Returns the sum of the values in the array. The return type is
float
if any value is a float; otherwise, it isint
. If the array is empty, it returns0
.
Example 1: Basic Usage
In this example, we calculate the sum of an array of integers.
Output:
In this case, the values 1
, 2
, 3
, 4
, and 5
are summed to produce 15
.
Example 2: Array with Floats
You can also use array_sum()
with an array of floating-point numbers.
Output:
Here, the sum of 1.5
, 2.5
, and 3.0
gives 7.0
.
Example 3: Ignoring Non-Numeric Values
The function automatically ignores non-numeric values in the array.
Output:
In this example, the values "apple"
and null
are ignored, and the sum of the remaining numeric values is 10.5
.
Example 4: Empty Array
If the array is empty, array_sum()
will return 0
.
Output:
Here, since the array is empty, the output indicates a sum of 0
.
Practical Usage:
array_sum()
is useful for:- Quickly computing totals from arrays of numeric values.
- Summing values in financial applications, statistical calculations, or data analysis tasks.
Summary:
array_sum($array)
calculates the total sum of all numeric values in an array.- It ignores non-numeric values and returns the total as an integer or float, depending on the input.
- This function is a straightforward and efficient way to sum elements in an array in PHP.