Loops

Course 1 · Ch 4
Loops: for, while, and foreach
Repeating code without repeating yourself — and the specific loop each situation calls for

Loops repeat a block of code until some condition stops them. PHP offers several loop types, and most beginner confusion isn't about syntax — it's about knowing which loop fits a given situation. This chapter covers all three main types and gives a clear rule of thumb for choosing between them.

for — When You Know How Many Times to Repeat

<?php for ($i = 1; $i <= 5; $i++) { echo "Count: $i<br>"; } ?>

A for loop has three parts separated by semicolons: a starting value ($i = 1), a continue-while condition ($i <= 5), and a step to run after each iteration ($i++). It's the natural choice whenever the number of repetitions is known or calculable ahead of time.

while — When You Don't Know How Many Times, Just the Stop Condition

<?php $attempts = 0; $found = false; while (!$found && $attempts < 3) { $attempts++; echo "Attempt $attempts<br>"; // imagine $found gets set true by some real check here } ?>

while checks its condition before each iteration and keeps going as long as it's true — well suited to situations like "keep retrying until successful, or until a max attempt count is hit," where the exact number of iterations isn't known in advance.

do...while — The "Check After" Variant

<?php $count = 10; do { echo "This runs at least once, even though $count < 5 is false<br>"; } while ($count < 5); ?>

do...while checks its condition after running the block, guaranteeing the block executes at least once regardless of the condition — genuinely useful for things like "show a menu, then keep re-showing it until the user picks 'quit'."

foreach — Purpose-Built for Arrays

<?php $colours = ["red", "green", "blue"]; foreach ($colours as $colour) { echo "$colour<br>"; } // With keys too — genuinely common for associative arrays $prices = ["apple" => 0.50, "banana" => 0.30]; foreach ($prices as $item => $price) { echo "$item costs £$price<br>"; } ?>

foreach is the idiomatic way to iterate over an array in PHP — there's no manual index counter to manage, and the as $key => $value form gives access to both the key and the value together. Arrays themselves are covered fully in Chapter 6; this is enough syntax to start using foreach productively now.

Choosing the right loop is mostly about the question you're answering
"Repeat exactly N times" → for. "Repeat until some condition becomes true/false, unknown count" → while. "Do this once, then keep repeating until done" → do...while. "Go through every item in this array" → foreach. Reaching for the right one by habit, rather than forcing every situation into a for loop, makes code noticeably more readable.

break and continue

<?php for ($i = 1; $i <= 10; $i++) { if ($i == 7) { break; // exits the loop entirely } if ($i % 2 == 0) { continue; // skips to the next iteration, without printing } echo "$i<br>"; } // prints 1, 3, 5 — stops completely once it reaches 7 ?>

break exits the loop immediately, skipping any remaining iterations entirely. continue skips only the rest of the current iteration and moves on to the next one — the loop itself keeps running.

Infinite loops are a genuinely common beginner mistake
A while loop whose condition never becomes false — often because the variable being checked is never updated inside the loop body — will run forever, typically freezing the script until PHP's execution time limit kills it. Always double-check that whatever the loop condition depends on is actually being changed somewhere inside the loop.

Comparing the Loop Types

LoopChecks conditionBest for
forBefore each iterationKnown/calculable repeat count
whileBefore each iterationUnknown count, condition-driven
do...whileAfter each iterationMust run at least once
foreachPer array elementIterating over arrays

Coding Challenges

Challenge 1

Use a for loop to echo the multiplication table for 7, from 7×1 up to 7×12, one line per result.

📄 View solution
Challenge 2

Use a while loop to echo every even number from 2 to 20. Then rewrite the same logic using continue inside a for loop that checks every number from 1 to 20, skipping the odd ones.

📄 View solution
Challenge 3

Create an array of 5 favourite foods. Use foreach to echo each one numbered (1. Pizza, 2. Sushi, etc.) — you'll need a counter variable you increment yourself, since plain foreach on a simple array doesn't give you a position number directly.

📄 View solution

Chapter 4 Quick Reference

  • for (init; condition; step) — known/calculable repeat count
  • while (condition) — checks before each run; unknown count, condition-driven
  • do { } while (condition); — checks after; guarantees at least one run
  • foreach ($array as $value) / as $key => $value — idiomatic array iteration
  • break — exits the loop entirely; continue — skips to the next iteration
  • Infinite loops — happen when a while condition's variable is never updated inside the loop
  • Next chapter: functions — defining, parameters, return values, scope