The sum of an array is the result of adding every element once. This is the classic accumulator pattern: start at 0, then $total += $value for each item.
total = 0
+ 1 → total = 1
+ 2 → total = 3
+ 3 → total = 6
+ 4 → total = 10
+ 5 → total = 15
Sum = 15
Code
PHP Programs
Start with a fixed array and a simple helper. Then read values from input, and finish by tracing a running total with negatives.
Example 1 — Sum of a Fixed Array
Use foreach to add every element into an accumulator.
PHP
<?php
function sumArray(array $arr): int
{
$total = 0;
foreach ($arr as $value) {
$total += $value;
}
return $total;
}
$array = [1, 2, 3, 4, 5];
echo "Sum of the array elements: " . sumArray($array) . "\n";
Output
Sum of the array elements: 15
How It Works
$total starts at 0.
foreach visits 1, 2, 3, 4, then 5.
Each visit does $total += $value.
The running values are 1, 3, 6, 10, then 15.
Return the final total after the loop.
Example 2 — Sum with User Input
Read $n, fill an array, then reuse the same summing helper.
PHP
<?php
function sumArray(array $arr): int
{
$total = 0;
foreach ($arr as $value) {
$total += $value;
}
return $total;
}
echo "Enter number of elements: ";
$n = (int) trim(fgets(STDIN));
if ($n < 0) {
throw new InvalidArgumentException("n must be nonnegative.");
}
$arr = [];
for ($i = 0; $i < $n; $i++) {
echo "Enter element " . ($i + 1) . ": ";
$arr[] = (int) trim(fgets(STDIN));
}
echo "Sum of the array elements: " . sumArray($arr) . "\n";
Output
Enter number of elements: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Sum of the array elements: 15
How It Works
Read the length $n and reject a negative size.
Push each input value into $arr in a second loop.
Call sumArray — input and summing stay separate.
If $n is 0, the array is empty and the sum is 0.
Same helper as Example 1, so testing stays easy.
Example 3 — Running Total with Negatives
Print the accumulator after each step so negatives are easy to see.