Find Sum of Array in PHP

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Arrays

What you’ll learn

  • The simplest way to compute a total using an accumulator ($sum += $value in a foreach).
  • 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).

Tip: you can include negatives (like -2). Empty input is treated as “no numbers”.

Live result
Press "Compute sum".

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

Pseudocode
function arraySum(arr):
    sum ← 0
    for each value in arr:
        sum ← sum + value
    return sum
1

Sum of a fixed array

This matches the classic example: {1,2,3,4,5} sums to 15.

php
<?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";
?>
2

Sum of an array (user input)

Reads n, then reads n integers from PHP CLI and accumulates the total.

php
<?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

Initialize $sum to 0, then loop with foreach ($arr as $value) and add each value: $sum += $value. Then echo $sum (or return it from a function).
Because 0 is the identity for addition. If you start from 0 and add every element once, you get exactly the total.
Nothing special is needed. The same loop works; negative values simply subtract from the total.
Use int when values are integers and within platform range. If values can exceed integer range or include decimals, choose a suitable numeric strategy (float or big-number libraries) carefully.
O(n) because you must look at each of the n elements at least once.

🔄 Input / output examples

ArraySum
{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.

n = 0

Empty array

The sum of zero numbers is 0. The loop runs zero times and $sum stays 0.

Overflow

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.

Input

Invalid reads

In PHP CLI, validate with is_numeric() before casting so you don’t process invalid values.

⏱️ Time and space complexity

ApproachTimeExtra space
One loop through n elementsO(n)O(1)

Summary

  • Pattern: $sum = 0, then $sum += $value for each element (often with foreach).
  • Use: keep a running accumulator and validate input before adding.
  • Complexity: O(n) time, O(1) extra space.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful