1.3 · Loops: for, while, foreach

Level 1 · Language basics

1.3Loops: for, while, foreach

Goal: repeat processing and iterate collections with for, while and above all foreach (the most used), controlling flow with break/continue.
Estimated time: 10 min · self-paced reading · If you only have 5 min: read “The essentials in 30s” + the diagram.

The essentials in 30 seconds

  • foreach = the everyday loop: foreach ($tab as $valeur) or as $cle => $valeur — iterate with no index to manage.
  • for = counter, while = condition: for when the count is known, while as long as a condition is true (and do...while at least once).
  • break exits, continue skips: and every loop must be able to end — beware infinite loops.

Running mini-case — Riad displays his catalogue in Constantine

Riad must display the catalogue of his showcase site: a list of services stored as an array. He first writes a for loop with a manual index — and displays one element too many because of an off-by-one error. He switches to foreach: each service displays with no index to manage, with htmlspecialchars for escaping. He adds a break to stop the search as soon as the service is found, and a for counter to number the pages. The catalogue displays complete, with no overflow.

Sequel to cases 1.1-1.2 — Riad moves from decisions to repetition.

1. for, while, do...while

Loops REPEAT processing. for: when you know the number of repetitions (or iterate with a counter) — for ($i = 0; $i < 10; $i++) { … }. while: as long as a condition is true (unknown count). do...while: runs at least once (test at the end). Caution: an infinite loop (condition that never becomes false, forgotten increment) blocks the script.

Riad numbers his pages with a bounded for and checks that his counter advances: no infinite loop will block the catalogue display.

2. foreach & break/continue

PHP's key loop is foreach: iterate an array — foreach ($tab as $valeur) (each value) or foreach ($tab as $cle => $valeur) (key → value pairs). Everywhere: displaying lists, processing database results. break exits the loop immediately; continue moves to the next iteration. In templates: alternative syntax foreach (…): … endforeach;.

Riad iterates his services with foreach, escapes each name with htmlspecialchars, and stops the search with break as soon as the service is found.

Common misinterpretation: "for + index is fine for iterating an array" or "displaying in a loop needs no escaping". No. Iterating an array with for + index reintroduces the off-by-one errors that foreach eliminates: foreach is simpler and safer. And any data displayed in a loop must be escaped (htmlspecialchars) — a loop displaying ten unescaped names is ten XSS vulnerabilities instead of one.
Loops foreach dominates in PHP for Counter, knownrepetition countwhile / do...while While acondition holds (unknown count)foreach Iterate anarray (most used)
foreach dominates in PHP
Text version of the diagram (SEO / screen readers / translation): 1) Count: Riad uses for to number pages (known bounds, checked increment). 2) Iterate: he displays each service with foreach, no manual index — no more extra element. 3) Control: break to stop the search, continue to skip, htmlspecialchars on every display. Lesson: foreach for collections, for for counters, and every loop ends.

🔎 Concrete example — 🔎 Concrete example — Iterating a collection

The dominant case in PHP, like Riad for his catalogue.

$produits = ['apple', 'banana', 'cherry'];
foreach ($produits as $produit) {
    echo htmlspecialchars($produit) . ' ';
}
// associative:
foreach ($config as $cle => $valeur) {
    echo $cle . ': ' . $valeur . ' ';
}

Reading: each element is handled with no index to manage — the as $cle => $valeur form for associatives.

Lesson: escape displayed data (htmlspecialchars) — a security reflex starting with loops.

Section vocabulary

Loop
Repeats processing instead of duplicating code; essential for handling collections or repeating an action.

Simple example: Riad's catalogue display, repeated per element.

What it is not: copying the same display block ten times.

Reflex: as soon as processing repeats, a loop.

for
Loop with a counter, when you know the repetition count: for ($i = 0; $i < 10; $i++) { ... } (initialisation; condition; increment).

Simple example: Numbering the catalogue pages of Riad.

What it is not: iterating an array with a manual index and off-by-one error.

Reflex: for = useful counter, checked bounds.

while / do...while
while: repeats AS LONG AS a condition is true (unknown count). do...while: runs at least once (test at the end).

Simple example: Riad re-reading lines while some remain.

What it is not: a while whose condition never changes (infinite).

Reflex: make sure the condition will end up false.

foreach
Loop to ITERATE an array (the most used): foreach ($tab as $valeur) (each value) or foreach ($tab as $cle => $valeur) (key → value pairs).

Simple example: The services displayed one by one by Riad.

What it is not: a for + $tab[$i] with overflow risk.

Reflex: array to iterate = foreach, keyed form if needed.

break / continue
break: EXITS the loop immediately. continue: MOVES to the next iteration. Beware INFINITE loops (condition that never becomes false).

Simple example: Riad's break as soon as the service is found.

What it is not: iterating 500 lines while the target is 3rd.

Reflex: break to stop, continue to skip.

In practice — In practice — Repeating and iterating with loops

  1. Write a for loop (e.g. display numbers 1 to 10) and a while loop (repeat while a condition is true).
  2. Iterate an array with foreach: `foreach ($produits as $produit) { ... }`, then with key => value on an associative array.
  3. Use break (exit as soon as an element is found) and continue (skip some elements) in a loop.
  4. Check that no loop is infinite (the condition ends up false) and spot the alternative `foreach (...): ... endforeach;` syntax for templates.
You repeat processing and iterate collections with for, while and above all foreach (the most used), controlling flow with break/continue — at the heart of data processing.

Ready-to-say script — suggesting foreach in code review (30 s)

"I suggest we convert this for loop to foreach: we iterate an array, so no manual index is needed — we eliminate the off-by-one risk. And let's add htmlspecialchars to the display, since we loop over displayed data."

Say in code review; show the before/after on the real loop.

Copy-paste template — catalogue displayed with foreach (escaped)

 $prestation) {
    echo ($i + 1) . '. ' . htmlspecialchars($prestation) . "\n";
}
$recherche = 'Shop';
foreach ($prestations as $prestation) {
    if ($prestation === $recherche) {
        echo 'Found: ' . htmlspecialchars($prestation);
        break;
    }
}

Catalogue in Constantine

Like Riad: foreach over services, computed order number, systematic htmlspecialchars — the catalogue displays complete and safe.

Search with stop

A break as soon as the element is found: no need to iterate the rest of the array once the target is located.

Numbered pages

A bounded for to number or repeat N times — the counter is the for's reason to exist, not iterating.

List in a template

In HTML, the foreach (...): ... endforeach; form reads better mixed with tags — same loop, adapted syntax.

✓ Best practices

  • Use foreach to iterate an array (simpler than for + index).
  • Reserve for for cases where the counter/index is genuinely useful.
  • Check that a while/for condition will end up false.

✗ Common pitfalls

  • Creating an infinite loop (forgotten increment, badly written condition).
  • Iterating an array with for + index when foreach is enough.
  • Displaying unescaped data in a loop (XSS).

Key takeaways

  • LOOPS repeat processing: `for` (with counter, known count), `while` (while a condition is true, unknown count), `do...while` (at least once).
  • FOREACH is THE key PHP loop: iterate an ARRAY — `foreach ($tab as $valeur)` or `foreach ($tab as $cle => $valeur)`. Everywhere (displaying lists, processing results).
  • `break` exits the loop, `continue` moves to the next iteration. Beware INFINITE LOOPS (condition that never becomes false → blocked script).
  • Alternative `foreach (...): ... endforeach;` syntax preferred in HTML TEMPLATES. Loops process SETS of data — at the heart of web applications.

48h challenge — apply tomorrow

Convert a for + index loop iterating an array into foreach (template above), add htmlspecialchars to the display and a break on a search. Compare before/after locally. 20 minutes is enough.

Section exit checklist
  • I choose for, while or foreach as appropriate — foreach for arrays.
  • I use break/continue aptly and my loops terminate.
  • I escape data displayed in my loops.
Self-assessment 1-5: do I iterate arrays with foreach and no manual index?do my loops display escaped data?

Frequently asked questions

When to use for, while or foreach — how to pick the right loop?

foreach: to ITERATE a collection (the most frequent case in PHP) — it handles iteration automatically, hence simpler and safer than for. Two forms: `as $valeur` and `as $cle => $valeur` (for associatives). for: when you need a COUNTER or a precise count, a specific step — but to simply iterate an array, foreach is preferable. while: when the end depends on a DYNAMIC condition, without knowing the count upfront — making sure it will end up false. In PHP web work, foreach dominates.

Why is foreach so central in PHP, and how to use it effectively?

PHP web development largely consists of HANDLING ARRAYS: query results, form data, configurations — and foreach is the ideal tool: simple, safe (no index, no infinite loop) and readable. Effectively: pick the right form (`as $valeur` or `as $cle => $valeur`), display with `htmlspecialchars`, use the alternative syntax in templates, combine with break/continue, and know array_map/filter/reduce (1.5) for transformations.

Check your understanding

What is PHP's key loop for iterating an array?

Additional resources (optional, to go further)

Level 1 examFresh, harder questions to test what you've learned