PHP Array Sum Function Explained: How to Calculate the Sum of an Array in PHP
As a developer, you know that PHP is a powerful language that allows you to create dynamic websites with ease. One of the most common tasks in web development
The array_sum() function adds up every value in an array and returns the total. It is one of the quickest ways to total a list of numbers in PHP — prices in a cart, scores in a test, or any numeric collection — without writing a loop yourself. This chapter covers its syntax, return type, how it handles non-numeric values and empty arrays, and several practical examples.
What is the Array Sum Function in PHP?
The array_sum() function in PHP is a built-in function that calculates and returns the sum of all the values in an array. It is a simple yet powerful function that can save you a lot of time and effort when working with arrays. The function takes a single parameter, which is the array you want to calculate the sum of.
Here's the basic syntax of the array_sum() function:
PHP array_sum syntax
array_sum(array $array): int|floatThe function takes an array as its only parameter and returns an int|float: if every value is an integer the result is an int, but as soon as any value is a float the result becomes a float. Both indexed and associative arrays work — keys are ignored, only the values are summed.
How to Use the Array Sum Function in PHP
Using the array_sum() function in PHP is quite straightforward. All you need to do is pass an array to the function, and it will return the sum of all the values in the array.
Here's an example:
PHP example of array_sum function usage
In this example, we define an array called $numbers containing five integers. We pass it to array_sum(), which returns the total. Finally, we display the result using echo.
Note: array_sum() automatically casts values to numbers. A numeric string like "3" or "4.5" is converted to its numeric value, while a non-numeric string such as "abc" is treated as 0 (and emits a warning in PHP 8+). So array_sum([1, "2", "abc"]) returns 3 (1 + 2 + 0).
The output of this code will be:
The sum of the numbers is: 15Real-World Examples of Using the Array Sum Function in PHP
Now that you know how to use the array_sum() function in PHP, let's take a look at some real-world examples of how this function can be used in web development.
Example 1: Calculating the Total Price of Items in a Shopping Cart
Suppose you are building an e-commerce website and you want to calculate the total price of all the items in a shopping cart. You can use the array_sum() function to easily calculate the total price.
Here's an example:
PHP Example 1: Calculating the Total Price using array_sum function
Here, we define a $cart array with product details. We extract the prices into a flat array using array_column(), sum them with array_sum(), and display the result.
The output of this code will be:
The total price of the items in the cart is: $60Example 2: Calculating the Average Score
In this example, we define a $scores array with five student grades. We calculate the average by dividing the sum of the scores by the item count(), then display the result.
PHP calculate average using array_sum
The output of this code will be:
The average score of the students is: 84array_sum() vs. array_product() and array_reduce()
array_sum() is purpose-built for one job — adding values. When you need a different kind of aggregation, reach for a related function:
- To multiply all values instead of adding them, use
array_product(). - For any custom accumulation (concatenation, conditional sums, summing a property), use
array_reduce(), which lets you supply your own callback.
Use array_sum() whenever a plain total is all you need — it is shorter and faster than the equivalent array_reduce() call.
Best Practices for Using the Array Sum Function in PHP
While the array_sum() function in PHP is quite simple to use, there are a few best practices you should keep in mind to ensure that you use it correctly and efficiently.
1. Check that the Input is an Array
Before you use the array_sum() function, it's important to ensure the input is actually an array. In PHP 8+, passing a non-array value throws a TypeError instead of a warning.
To check if a variable is an array, you can use the is_array() function. Here's an example:
PHP check if the input is an array
if (is_array($numbers)) {
$sum = array_sum($numbers);
} else {
// handle the error
}We verify the variable with is_array() before calling array_sum(). If it's not an array, we handle the error appropriately.
2. Handle Empty Arrays
If you pass an empty array to the array_sum() function, it will return a value of 0. While this might be the correct value in some cases, it's important to handle empty arrays in a way that makes sense for your application.
For example, if you're calculating the average score of students in a class and there are no students, you might want to display a message indicating that there are no scores to average.
PHP Handle Empty Arrays while using array_sum
if (empty($scores)) {
echo "There are no scores to average.";
} else {
$average_score = array_sum($scores) / count($scores);
echo "The average score of the students is: " . $average_score;
}We check if $scores is empty using empty(). If it is, we show a message; otherwise, we calculate and display the average.
Conclusion
The array_sum() function in PHP is a simple yet powerful function that can save you a lot of time and effort when working with arrays. It allows you to easily calculate the sum of all the values in an array, which can be useful in a wide range of applications.
In this article, we provided a comprehensive guide on how to use the array_sum() function in PHP, including real-world examples and best practices. By following these guidelines, you can ensure that you use the function correctly and efficiently, and create more reliable PHP applications.