PHP Loops - While Loop
Executes a block of code a specified number of times, or while a specified condition is true.
PHP Loops
When writing code, you often need to repeat the same block of code over and over. We can use loop statements in our code to accomplish this task.
In PHP, the following loop statements are provided:
- while - Loops through a block of code as long as the specified condition is true
- do...while - Executes a block of code once, and then repeats the loop as long as the specified condition is true
- for - Loops through a block of code a specified number of times
- foreach - Loops through a block of code for each element in an array
While Loop
The while loop will repeatedly execute a block of code until the specified condition is no longer true.
Syntax
while (condition)
{
code to be executed;
}
Example
The following example sets the variable i to 1 ($i=1;).
Then, as long as i is less than or equal to 5, the while loop will continue to run. Each time the loop runs, i will increment by 1:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>
</body>
</html>
Output:
do...while Statement
The do...while statement will execute the code block at least once, and then it will check the condition. As long as the condition is true, the loop will repeat.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The following example sets the variable i to 1 ($i=1;).
Then, the do...while loop begins. It increments the variable i by 1 and then outputs it. It checks the condition (i is less than or equal to 5), and as long as i is less than or equal to 5, the loop will continue to run:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Output:
For loops and foreach loops will be explained in the next chapter.