PHP: Loop Structures
Computers excel at repetitive work. Loops let you repeat an operation hundreds or thousands of times with just a few lines of code — generating tables, iterating through user lists, calculating totals — all effortless.
1. The while Loop
Repeats as long as a condition is true. Check first, execute later.
<?php
$i = 1;
while ($i <= 5) {
echo "Round {$i}<br>";
$i++;
}
// Outputs rounds 1 through 5
?>
Flowchart:
Initialize → [Check condition] → true → Execute loop body → Update variable → Go back to check
↓ false
Exit
true, you get an infinite loop and your program hangs. Before writing every while, ask yourself: is there code inside the loop that will eventually make the condition false?
2. The do...while Loop
The only difference from while: execute once first, then check. This guarantees the loop body runs at least once.
<?php
$i = 10;
do {
echo "Executed!<br>";
$i++;
} while ($i < 5);
// Even though the condition is false from the start, it still outputs "Executed!" once.
?>
| while | do...while | |
|---|---|---|
| Check timing | Check first, execute later | Execute first, check later |
| Runs at least once? | ❌ May run 0 times | ✅ Always at least once |
| Frequency of use | Common | Infrequent |
3. The for Loop
for combines initialization, condition, and iteration update all in one place — it's the most commonly used loop:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Round {$i}<br>";
}
// Outputs 1 through 5
?>
Three parts:
for (initialization; condition; action-after-each-iteration) {
// loop body
}
▶ Example: Multiplication Table with for
<?php
echo "<table border='1'>";
for ($i = 1; $i <= 9; $i++) {
echo "<tr>";
for ($j = 1; $j <= $i; $j++) {
echo "<td>{$j}×{$i}=" . ($i * $j) . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Output:
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
... (9x9=81)
4. The foreach Loop
foreach is PHP's most distinctive loop — designed specifically for traversing arrays. Its syntax is so clean it's almost addictive:
<?php
// Loop through an indexed array (value only)
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo "{$fruit}<br>";
}
// Loop through an associative array (key + value)
$user = [
"name" => "John",
"age" => 25,
"city" => "New York"
];
foreach ($user as $key => $value) {
echo "{$key}: {$value}<br>";
}
// name: John
// age: 25
// city: New York
?>
foreach is the most-used loop in PHP. Memorize two patterns: foreach ($arr as $val) for value only; foreach ($arr as $key => $val) when you need both key and value.
5. break and continue
| Keyword | Action |
|---|---|
break |
Immediately exits the entire loop — no more iterations |
continue |
Skips the rest of the current iteration and moves to the next one |
▶ Example: break and continue
Output:
1 2 3 4
<?php
// break: stop at 5
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop
}
echo $i . " ";
}
// Output: 1 2 3 4
// continue: skip 5
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
continue; // Skip this iteration
}
echo $i . " ";
}
// Output: 1 2 3 4 6 7 8 9 10
?>
Output:
1 2 3 4 6 7 8 9 10
break 2; exits two levels of nested loops, and continue 2; skips the current iteration of the outer loop. The number after break/continue indicates how many nesting levels to affect.
6. Mixing Loops with HTML
The alternative syntax makes loops far more elegant inside HTML templates:
▶ Example: Generating an HTML Table with foreach
Output:
(no visible output)
<?php
$students = [
["name" => "Alice", "score" => 92],
["name" => "Bob", "score" => 85],
["name" => "Charlie", "score" => 78],
["name" => "Diana", "score" => 95],
];
?>
<table border="1">
<tr>
<th>Name</th>
<th>Score</th>
<th>Grade</th>
</tr>
<?php foreach ($students as $s): ?>
<tr>
<td><?= $s['name'] ?></td>
<td><?= $s['score'] ?></td>
<td>
<?php if ($s['score'] >= 90): ?>
🌟 Excellent
<?php elseif ($s['score'] >= 80): ?>
👍 Good
<?php else: ?>
📚 Keep Trying
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
Output:
<table border="1">
<tr><th>Name</th><th>Score</th><th>Grade</th></tr>
<tr><td>Alice</td><td>92</td><td>Excellent</td></tr>
<tr><td>Bob</td><td>85</td><td>Good</td></tr>
<tr><td>Charlie</td><td>78</td><td>Keep Trying</td></tr>
<tr><td>Diana</td><td>95</td><td>Excellent</td></tr>
</table>
This example shows PHP's core magic — turning array data into a complete HTML table with just a handful of lines.
7. Choosing the Right Loop
| Scenario | Recommended Loop |
|---|---|
| Traversing an array | foreach |
| Fixed number of iterations (e.g., 1 to 10) | for |
| Unknown number of iterations, but known condition | while |
| Must execute at least once | do...while (rarely used) |
| Nested 2D array / table traversal | Nested for or nested foreach |
foreach is the absolute workhorse (you'll traverse arrays constantly). Next comes for for counted loops. while is occasionally used when reading files or database result sets. do...while is almost never used.
❓ FAQ
$i++ and $i += 2 in a for loop?$i++ increments by 1 each time. $i += 2 increments by 2 (step size of 2). Use the latter to output only odd or even numbers.foreach ($arr as $val) works on a copy — modifying $val doesn't affect the original array. If you prepend & to $val (reference), modifications do affect the original. We'll cover this in detail in Lesson 12 (Advanced Functions).📖 Summary
whilechecks first, executes later — may run zero times if the condition is falsedo...whileexecutes first, checks later — always runs at least onceforbundles initialization, condition, and iteration update together — best for fixed-count loopsforeachis PHP's most-used loop — traverse arrays with$arr as $valor$arr as $key => $valbreakexits the loop;continueskips the current iteration- Alternative syntax (
for (): ... endfor;/foreach (): ... endforeach;) keeps HTML mix-ins clean
📝 Exercises
- Use a for loop to output all even numbers from 1 to 100 (hint: step size of 2, or
% 2 == 0). - Create an associative array storing 5 friends' names and phone numbers, then use foreach to display them as an HTML table.
- Use nested loops to print a pyramid of asterisks: row 1 has 1 star, row 2 has 3, ... row 5 has 9 — center-aligned.