PHP while Loop
The PHP `while` loop is used to execute a block of code as long as a specified condition is true. It is an entry control loop, which means the condition is evaluated before entering the loop. The `while` loop is particularly useful when the number of iterations is not known beforehand.
Syntax
while (condition) {
// code to be executed
}
Flowchart

Example
<?php
$n = 1;
while ($n <= 10) {
echo "$n<br/>";
$n++;
}
?>
Output
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Example
The `while` loop continues execution as long as the specified condition is true. If the condition is initially false, the loop body will not execute.
<?php
$x = 5;
while ($x < 10) {
echo "Value is: $x<br/>";
$x++;
}
?>
Output
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Difference between while, do-while, and for loops
while Loop | do-while Loop | for Loop |
---|---|---|
Executes only if the condition is true. | Executes at least once, even if the condition is false. | Executes a specific number of times. |
Condition is checked before the loop body. | Condition is checked after the loop body. | Initialization, condition, and increment/decrement are set in one line. |