How to Use the PHP array_sum() Function

09/07/2021

Contents

In this article, you will learn how to use the PHP array_sum() function.

PHP array_sum() Function

The array_sum() function in PHP takes an array as an argument and returns the sum of all the values in the array.

Syntax:
array_sum(array $array) : number
Example:
<?php
  $numbers = array(1, 2, 3, 4, 5);
  $sum = array_sum($numbers);

  // $sum will be equal to 15
?>

The array_sum function in PHP can be useful for quickly calculating the sum of all values in an array, especially if you need to perform mathematical operations on the values.

Here’s a few additional things to keep in mind when using the array_sum() function:

  • Numeric strings: If the array contains string values that represent numbers (e.g. “10”), they will be treated as 0 (zero) unless they contain a numeric value (e.g. “10.5”).
  • Empty arrays: If the array passed to array_sum is empty, it will return 0.
  • Recursive arrays: If the array contains sub-arrays, array_sum will only sum the values of the first level of the array. To sum the values of all levels, you’ll need to use a recursive function.
  • Types of arrays: You can use the array_sum function on any type of array, including indexed arrays, associative arrays, and multidimensional arrays.

Here’s an example of using array_sum on an associative array:

<?php
  $prices = array("item1" => 10, "item2" => 20, "item3" => 30);
  $sum = array_sum($prices);

  // $sum will be equal to 60
?>

In this example, array_sum takes an associative array as an argument and returns the sum of all its values, which is 60.