PHP Loops
A loop is a control structure that repeats a block of code multiple times. Instead of writing the same code ten times for ten similar tasks, a loop handles all repetitions automatically. PHP provides four types of loops: for, while, do-while, and foreach. Each is suited to different scenarios.
The for Loop
The for loop is best when the number of iterations is known in advance. It uses three expressions: an initializer, a condition, and an increment.
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: " . $i . "<br>";
}
// Outputs:
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4
// Iteration: 5
?>
The loop starts with $i = 1. Before each iteration, it checks if $i <= 5. After each iteration, it runs $i++. When the condition becomes false, the loop ends.
Counting Down
<?php
for ($i = 10; $i >= 1; $i--) {
echo $i . " ";
}
echo "Launch!";
// Outputs: 10 9 8 7 6 5 4 3 2 1 Launch!
?>
Loop with Step
<?php
for ($i = 0; $i <= 20; $i += 5) {
echo $i . " "; // Outputs: 0 5 10 15 20
}
?>
The while Loop
The while loop continues running as long as the condition is true. It is used when the number of iterations is not known beforehand.
<?php
$count = 1;
while ($count <= 5) {
echo "Count: " . $count . "<br>";
$count++;
}
// Outputs:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
?>
The condition is checked before the loop body runs. If the condition is false from the very beginning, the loop body never executes.
Practical while Example — Processing a Number
<?php
$number = 1;
while ($number < 1000) {
$number *= 2;
}
echo $number; // Outputs: 1024 (first power of 2 that exceeds 1000)
?>
The do-while Loop
The do-while loop is similar to while, but the code block runs at least once because the condition is checked after the block executes — not before.
<?php
$number = 10;
do {
echo "Number is: " . $number . "<br>";
$number++;
} while ($number < 10);
// Outputs: Number is: 10
// Even though 10 is NOT less than 10, the block ran once before the check.
?>
The do-while loop is useful for input validation scenarios where the user must provide data at least once before it can be checked.
The foreach Loop
The foreach loop is designed specifically for iterating over arrays. It automatically handles the counter and automatically moves to the next element in each iteration.
Indexed Array
<?php
$fruits = ["apple", "banana", "cherry", "date"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
// Outputs:
// apple
// banana
// cherry
// date
?>
Associative Array
<?php
$person = [
"name" => "Carlos",
"age" => 28,
"email" => "carlos@example.com"
];
foreach ($person as $key => $value) {
echo $key . ": " . $value . "<br>";
}
// Outputs:
// name: Carlos
// age: 28
// email: carlos@example.com
?>
Loop Control — break and continue
break — Stop the Loop Early
The break statement immediately exits the loop, skipping any remaining iterations.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i === 5) {
break; // Stop the loop when i reaches 5
}
echo $i . " ";
}
// Outputs: 1 2 3 4
?>
continue — Skip the Current Iteration
The continue statement skips the rest of the current iteration and moves to the next one.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 === 0) {
continue; // Skip even numbers
}
echo $i . " ";
}
// Outputs: 1 3 5 7 9
?>
Nested Loops
Loops can be placed inside other loops. Each iteration of the outer loop triggers a full run of the inner loop.
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
echo "[$row,$col] ";
}
echo "<br>";
}
// Outputs:
// [1,1] [1,2] [1,3]
// [2,1] [2,2] [2,3]
// [3,1] [3,2] [3,3]
?>
Choosing the Right Loop
| Loop | Best Used When |
|---|---|
| for | Number of iterations is known in advance |
| while | Loop until an unknown condition becomes false |
| do-while | Block must run at least once before checking the condition |
| foreach | Iterating over every element in an array |
Key Points
- The
forloop uses an initializer, condition, and increment expression. - The
whileloop runs as long as its condition is true — checked before each iteration. - The
do-whileloop always runs the block at least once — condition checked after. - The
foreachloop iterates over each element in an array without manual indexing. breakexits the loop immediately;continueskips the current iteration and moves to the next.- Avoid infinite loops — always ensure the condition will eventually become false.
