Understand the while loop in PHP for repeated execution based on conditions. Includes syntax, examples, and tips to write cleaner looping logic in PHP.
while
LoopThe while
loop is one of the simplest and most commonly used loops in PHP. It allows you to run a block of code as long as a specified condition is true.
The basic syntax of a while
loop is:
while (condition) {
// Code to execute as long as condition is true
}
true
, the code inside the loop runs.false
, the loop stops.false
from the start, the loop will not run at all.You can also use an alternate form, especially useful in templates or HTML-heavy code:
while (condition):
// Code to execute
endwhile;
<?php
$i = 1;
while ($i <= 10) {
echo $i . " ";
$i++; // Increases $i by 1 each time
}
?>
Output:
1 2 3 4 5 6 7 8 9 10
๐ In this example:
$i = 1
.$i <= 10
.$i
increases by 1 using $i++
.<?php
$i = 1;
while ($i <= 10):
echo $i . " ";
$i++;
endwhile;
?>
This gives the same output as Example 1, just with a different style of writing.
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP - While Loop Example</title>
</head>
<body>
<?php
$x = 1;
while ($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
Output in browser:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
$i
or $x
) usually gets updated inside the loop to avoid infinite looping..
to concatenate (join) strings and variables, like in echo $i . " ";
.further reading: