PHP Loops
Loops execute a block of code repeatedly as long as a condition is true. PHP provides four loop types: while, do-while, for, and foreach.
while and do-while Loops
A while loop checks the condition before each iteration. A do-while loop always executes at least once because the condition is checked after the body.
<?php
// while loop
$i = 1;
while ($i <= 5) {
echo "Count: $i\n";
$i++;
}
// do-while loop — runs at least once
$n = 10;
do {
echo "n = $n\n";
$n++;
} while ($n < 5);
// Output: n = 10 (runs once even though 10 < 5 is false)
?>
for Loop
The for loop is ideal when you know the exact number of iterations. It combines initialization, condition, and increment in one line.
<?php
// Basic for loop
for ($i = 0; $i < 5; $i++) {
echo "Item $i\n";
}
// Countdown
for ($i = 5; $i >= 1; $i--) {
echo "$i ";
}
// Output: 5 4 3 2 1
// Nested loops — multiplication table
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
echo $row * $col . "\t";
}
echo "\n";
}
?>
foreach Loop
The foreach loop is designed for iterating over arrays. Use the key => value syntax to access both keys and values.
<?php
// Indexed array
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "\n";
}
// Associative array with key => value
$person = ["name" => "Alice", "age" => 30, "city" => "NYC"];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
// break and continue
for ($i = 0; $i < 10; $i++) {
if ($i === 5) break; // stop loop at 5
if ($i % 2 === 0) continue; // skip even numbers
echo $i . " ";
}
// Output: 1 3
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.