How to Find Sum of Array in PHP: Simple Guide
To find the sum of an array in PHP, use the
array_sum() function which adds all the values in the array and returns the total. Simply pass your array as an argument to array_sum() to get the sum.Syntax
The syntax to find the sum of an array in PHP is simple:
array_sum(array $array): int|float
Here, $array is the array of numbers you want to add. The function returns the total sum of all values.
php
array_sum(array $array): int|float
Example
This example shows how to use array_sum() to add numbers in an array and print the result.
php
<?php $numbers = [10, 20, 30, 40]; $total = array_sum($numbers); echo "The sum is: " . $total; ?>
Output
The sum is: 100
Common Pitfalls
Common mistakes include passing non-numeric values or forgetting that array_sum() only sums values, not keys.
Also, if the array is empty, array_sum() returns 0.
php
<?php // Wrong: summing keys instead of values $array = [1 => 10, 2 => 20, 3 => 30]; // This sums values, not keys $sum = array_sum($array); echo "Sum of values: " . $sum . "\n"; // Right: if you want to sum keys, use array_keys() $sumKeys = array_sum(array_keys($array)); echo "Sum of keys: " . $sumKeys; ?>
Output
Sum of values: 60
Sum of keys: 6
Quick Reference
| Function | Description |
|---|---|
| array_sum($array) | Returns the sum of all values in the array |
| array_keys($array) | Returns all keys of the array (useful if you want to sum keys) |
| empty array | Returns 0 when passed to array_sum() |
Key Takeaways
Use array_sum() to quickly find the sum of all values in a PHP array.
array_sum() returns 0 for empty arrays, so no errors occur.
array_sum() sums values, not keys; use array_keys() if you want to sum keys.
Passing non-numeric values may lead to unexpected results or warnings.
Always ensure your array contains numbers to get correct sums.