PHP For Loop Infinite Loop Syntax
This article explains the exact syntax required to create an infinite
loop using the for loop construct in PHP. You will learn
the minimalist code structure needed to run a continuous loop, how the
underlying logic works, and how to safely exit the loop using control
statements.
To create an infinite loop using the for construct in
PHP, you omit all three expressions inside the parentheses. The syntax
is as follows:
for (;;) {
// Code to be executed infinitely
}How It Works
A standard PHP for loop contains three expressions
separated by semicolons:
for (initialization; condition; increment)
- Initialization: Run once before the loop begins.
- Condition: Evaluated before each iteration. If
true, the loop continues; iffalse, the loop ends. - Increment: Run at the end of each iteration.
When you write for (;;), you omit all three expressions.
PHP interprets the empty condition expression as implicitly
true. Because there is no condition that can evaluate to
false, the loop will run indefinitely.
Breaking the Infinite Loop
To prevent the infinite loop from crashing your script or exhausting
server resources, you can use the break statement to exit
the loop when a specific condition is met:
$counter = 0;
for (;;) {
echo "Iteration: $counter\n";
$counter++;
if ($counter >= 10) {
break; // Exits the loop immediately
}
}