Loops in PHP execute a block of code multiple times based on a condition. They help reduce redundant code.
✅ Repeats the block as long as the condition is true
.
Syntax:
while (condition) {
// Code to execute
}
Example:
$x = 1;
while ($x <= 5) {
echo "Number: $x <br>";
$x++;
}
✔ Prints numbers 1 to 5.
✅ Executes the block at least once, then checks the condition.
Syntax:
do {
// Code to execute
} while (condition);
$x = 1;
do {
echo "Number: $x <br>";
$x++;
} while ($x <= 5);
✔ Runs at least once, even if $x
is initially greater than 5.
✅ Used when the number of iterations is known.
for (initialization; condition; increment/decrement) {
// Code to execute
}