while loops are the simplest type of loop. This executes the nested statements repeatedly, as long as the while expression evaluates to TRUE.
Structure of while
Syntax | Description |
---|---|
while(expr) stmt; |
stmt is repeatedly executed when expr is true |
<?php
$var = 0;
while($var < 3) // expression will be TRUE till third comparison
{
echo "$var\r\n"; // statement will be executed three times
$var++; // increase $var by one
sleep(1); // 1 second delay
}
?>
[result]
0
1
2
<?php
$var = 0;
while(1) // expression will always be TRUE
{
echo "$var\r\n";
$var++; // increase $var by one, $var = 1, 2, 3, …
sleep(1); // 1 second delay
}
?>