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

Updated: January 10, 2024 By: Guest Contributor Post a comment

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.