Lesson 10 of 100
Loops12 min5 checksPHP 8.5

Loop over arrays with foreach and build a total

Learn how foreach visits every value in an array, how to read keys too, and how to accumulate a total that safely returns 0 for empty input.

01 · THE IDEAREAD → TRY → LEARN

Why loops matter

Most programs process collections: a list of scores, the lines of an order, the items in a cart. A loop lets you write the processing steps once and run them for every element. In PHP, the most natural loop for arrays is foreach.

The two forms of foreach

The first form gives you each value in turn:

foreach ($array as $value) { ... }

On every pass, PHP copies the current element into $value and runs the loop body. When the elements run out, the loop ends and the program continues after the closing brace.

Example
<?php
$scores = [4, 8, 15];
foreach ($scores as $score) {
    echo "Score: $score\n";
}
Output
Score: 4
Score: 8
Score: 15

The loop body ran three times because the array has three elements. You never wrote an index, a counter or a length check. That is the main appeal of foreach: there is no off-by-one error to make.

The second form also exposes the key:

foreach ($array as $key => $value) { ... }

This matters for associative arrays, where the keys carry meaning.

Example
<?php
$prices = ['tea' => 3, 'coffee' => 4];
foreach ($prices as $item => $price) {
    echo "$item costs $price\n";
}
Output
tea costs 3
coffee costs 4

Elements are visited in the order they are stored in the array. Also, foreach does not move the array's internal pointer, so functions such as current() and key() are unaffected by it.

Accumulating a total

A very common loop pattern is the accumulator:

  1. Create a variable before the loop and give it a neutral starting value.
  2. Update that variable on each pass.
  3. Use or return it after the loop.

For addition, the neutral starting value is 0. Adding zero changes nothing, so it is the right place to begin. This choice also solves the empty-input case for free: if the array has no elements, the loop body never runs, and the function returns the starting value, 0. That is the mathematically sensible answer for the sum of nothing.

Example
<?php
function addAll(array $numbers): int
{
    $total = 0;
    foreach ($numbers as $number) {
        $total += $number;
    }
    return $total;
}
echo json_encode([addAll([2, 3, 5]), addAll([])]);
Output
[10,0]

The expression $total += $number is shorthand for $total = $total + $number. The variable $total is created outside the loop so that it survives from one pass to the next.

Common mistakes

  • Resetting the total inside the loop. If $total = 0 is written inside the braces, every pass throws away the previous work and you only get the last element.
  • Starting from the first element and then looping over all of them. This counts the first element twice. Starting from 0 avoids special cases.
  • Forgetting to return after the loop. Returning inside the loop body ends the function on the first pass.
  • Passing a non-iterable value. foreach raises a warning when given something that is not an array or object, such as null. Type declarations like array $numbers catch this earlier.
  • Iterating by reference carelessly. Writing foreach ($arr as &$value) lets you modify elements in place, but $value stays a reference to the last element afterwards. Call unset($value) after such a loop. You do not need references for summing.

Worked reasoning for the exercise

Suppose the input is [1, 2, 3, 4]. Before the loop, the total is 0. After the first pass it is 1, then 3, then 6, then 10. The loop ends and 10 is returned. With [], no pass happens, so the answer stays 0. With negative numbers such as [-5, -10], the same steps give -15, because adding a negative number simply lowers the total.

Exercise contract

Write a function named sumNumbers that takes one array of integers and returns their sum as an integer. An empty array must return 0. The checks use five inputs: an empty array, a single element, several positive numbers, a mix of positive and negative numbers, and only negative numbers. Your function should return the value, not print it.

Recap

  • foreach ($items as $item) visits every value without manual indexing.
  • foreach ($items as $key => $item) also gives you each key.
  • Initialize an accumulator before the loop, update it inside, and return it after.
  • Starting a sum at 0 makes empty input work naturally.
Before you start

Arrays · Variables

You’ll practice
  • Visit each value with foreach
  • Accumulate a total that handles empty input
Your task

Make sumNumbers() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.