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.
$scores = [4, 8, 15];
foreach ($scores as $score) {
echo "Score: $score\n";
}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.
$prices = ['tea' => 3, 'coffee' => 4];
foreach ($prices as $item => $price) {
echo "$item costs $price\n";
}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:
- Create a variable before the loop and give it a neutral starting value.
- Update that variable on each pass.
- 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.
function addAll(array $numbers): int
{
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo json_encode([addAll([2, 3, 5]), addAll([])]);[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 = 0is 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
0avoids 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.
foreachraises a warning when given something that is not an array or object, such asnull. Type declarations likearray $numberscatch this earlier. - Iterating by reference carelessly. Writing
foreach ($arr as &$value)lets you modify elements in place, but$valuestays a reference to the last element afterwards. Callunset($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
0makes empty input work naturally.
Arrays · Variables
- Visit each value with foreach
- Accumulate a total that handles empty input