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:

array_sum(array $array): float|int

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 is int. If the array is empty, it returns 0.

Example 1: Basic Usage

In this example, we calculate the sum of an array of integers.

<?php $array = [1, 2, 3, 4, 5]; $total = array_sum($array); echo "The sum is: " . $total; // Output: The sum is: 15 ?>

Output:

The sum is: 15

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.

<?php $array = [1.5, 2.5, 3.0]; $total = array_sum($array); echo "The sum is: " . $total; // Output: The sum is: 7.0 ?>

Output:

The sum is: 7

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.

<?php $array = [1, "2", 3, "apple", 4.5, null]; $total = array_sum($array); echo "The sum is: " . $total; // Output: The sum is: 10.5 ?>

Output:

The sum is: 10.5

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.

<?php $array = []; $total = array_sum($array); echo "The sum is: " . $total; // Output: The sum is: 0 ?>

Output:

The sum is: 0

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.