Sling Academy
Home/PHP/Ways to Calculate the Sum of an Array in PHP (7 examples)

Ways to Calculate the Sum of an Array in PHP (7 examples)

Last updated: January 10, 2024

Introduction

PHP, as a server-side scripting language, offers a wide range of functions to manipulate arrays – one of the most fundamental data structures used in programming. Arrays are often used to contain collections of data such as numbers, and it is a common task to calculate the sum of these numbers. Whether you’re a beginner or an experienced developer, understanding different methods to accomplish this task can be very useful in your coding journey.

Using array_sum()

The simplest and most straightforward way to calculate the sum of an array in PHP is by using the built-in function array_sum(). Here’s how you can use it:

$numbers = [1, 2, 3, 4, 5];
$sum = array_sum($numbers);
echo $sum;  // Outputs: 15

This function works with both integer and floating-point numbers and will ignore non-numeric values.

Looping through the Array

If you need more control over the calculation process or want to perform additional operations while calculating the sum, you can loop through the array. The commonly used loops are for, foreach, and while loops.

Using for Loop

$numbers = [1, 2, 3, 4, 5];
$sum = 0;
for ($i = 0; $i < count($numbers); $i++) {
    $sum += $numbers[$i];
}
echo $sum;

Using foreach Loop

$numbers = [1, 2, 3, 4, 5];
$sum = 0;
foreach ($numbers as $number) {
    $sum += $number;
}
echo $sum;

Using while Loop

$numbers = [1, 2, 3, 4, 5];
$sum = 0;
$i = 0;
while ($i < count($numbers)) {
    $sum += $numbers[$i];
    $i++;
}
echo $sum;

Remember that when using loops, especially for and while, be careful with the loop conditions to avoid off-by-one errors or infinite loops.

Functional Programming with array_reduce()

PHP’s array_reduce() function allows you to iteratively reduce an array to a single value using a callback function. You can use this to sum the values in an array:

$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum;

The array_reduce() function is particularly powerful because of its flexibility; you can adapt the callback function to implement any custom logic for reducing an array.

Summing Multidimensional Arrays

When working with multidimensional arrays, you’ll need to flatten the array or use a recursive approach to calculate the sum of all values:

Flattening the Array then Summing

PHP 7.4 introduced array_merge which can be used in conjunction with the spread operator to flatten arrays.

$numbers = [[1, 2], [3, 4], 5];
$flatArray = array_merge([], ...$numbers);
$sum = array_sum($flatArray);
echo $sum;  // Outputs: 15

Custom Recursive Function

function array_sum_recursive($array) {
    $sum = 0;
    array_walk_recursive($array, function($item) use (&$sum) {
        $sum += $item;
    });
    return $sum;
}

$numbers = [[1, 2], [3, 4], 5];
$sum = array_sum_recursive($numbers);
echo $sum;  // Outputs: 15

This function leverages array_walk_recursive() which applies a user-function recursively to each member of the array.

Conclusion

Calculating the sum of an array in PHP can be done using various techniques depending on the complexity of the task. While array_sum() offers an efficient built-in solution for single-dimensional arrays, looping constructs give you finer control over the process, and array_reduce() allows for more complex reduction logic. For multidimensional arrays, both flattening and recursive strategies have their use cases. With this knowledge, you can choose the most suitable method based on your requirements in different situations.

Next Article: 3 Ways to Calculate the Product of an Array in PHP

Previous Article: PHP Array Slicing: A Practical Guide

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array