Find Sum of Array in PHP
What you’ll learn
- The simplest way to compute a total using an accumulator (
$sum += $valuein aforeach). - How to write a clean PHP program for a fixed array and for user input.
- Common edge cases: empty input, negatives, and overflow.
Overview
To find the sum of an array, you visit each element exactly once and keep adding it to a running total. This is one of the most common patterns in programming, and it teaches you how loops and arrays work together.
Two programs
Example 1 sums {1,2,3,4,5}. Example 2 reads n and then n integers from the user.
Live preview
Paste numbers like 10, -2, 7 and see the computed sum instantly.
Safe sum type
We keep totals as integers in PHP for typical interview-sized inputs.
Live preview
Enter integers separated by commas or spaces (example: 1 2 3 or 1, 2, 3).
Algorithm
Goal: compute the total of every element in $arr (same idea as $arr[0] + $arr[1] + ...).
Initialize
Set sum = 0.
Loop through the array
For each element in the array (for example foreach ($arr as $value)), add the element into $sum.
Return or print
After the loop, $sum is the total.
📜 Pseudocode
function arraySum(arr):
sum ← 0
for each value in arr:
sum ← sum + value
return sumSum of a fixed array
This matches the classic example: {1,2,3,4,5} sums to 15.
<?php
function sumArray(array $arr): int
{
$sum = 0;
foreach ($arr as $value) {
$sum += $value;
}
return $sum;
}
$array = [1, 2, 3, 4, 5];
$sum = sumArray($array);
echo "Sum of the array elements: $sum\n";
?>Sum of an array (user input)
Reads n, then reads n integers from PHP CLI and accumulates the total.
<?php
echo "Enter number of elements: ";
$rawN = trim(fgets(STDIN));
if (!is_numeric($rawN) || (int)$rawN < 0) {
echo "Invalid n.\n";
exit(1);
}
$n = (int)$rawN;
$sum = 0;
for ($i = 0; $i < $n; $i++) {
echo "Enter element " . ($i + 1) . ": ";
$rawValue = trim(fgets(STDIN));
if (!is_numeric($rawValue)) {
echo "Invalid input.\n";
exit(1);
}
$sum += (int)$rawValue;
}
echo "Sum of the array elements: $sum\n";
?>❓ FAQ
🔄 Input / output examples
| Array | Sum |
|---|---|
{1,2,3,4,5} | 15 |
{10,-2,7} | 15 |
{} (n=0) | 0 |
Edge cases and pitfalls
Summing is simple, but these details keep your solution correct in interviews.
Empty array
The sum of zero numbers is 0. The loop runs zero times and $sum stays 0.
Total may exceed int
If numbers are very large (or there are many), integer overflow can still happen depending on platform limits. Use suitable numeric types or big-number libraries when needed.
Invalid reads
In PHP CLI, validate with is_numeric() before casting so you don’t process invalid values.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| One loop through n elements | O(n) | O(1) |
Summary
- Pattern:
$sum = 0, then$sum += $valuefor each element (often withforeach). - Use: keep a running accumulator and validate input before adding.
- Complexity:
O(n)time,O(1)extra space.
The “sum of an array” program is the simplest example of the accumulator pattern: start with $sum = 0, then add each element once. This idea appears everywhere: totals, averages, dot products, and prefix sums.
9 people found this page helpful
