PHP Loops -While Loop


Loops execute a block of code a specified number of times, or repeatedly execute a block of code while a specified condition is true.


PHP Loops

When you are writing code, you often need the same block of code to run repeatedly over and over again. We can use loop statements in the 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- First executes the block of code once, 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 becomes false.

Syntax

while (条件)
{
    要执行的代码;
}

Examples

The following example first sets a variableito the value 1 ($i=1;).

Then, as long asiis less than or equal to 5, the while loop will continue to run. Each time the loop runs,iit will be incremented by 1:

<html>
<body>

<?php
$i=1;
while($i<=5)
{
    echo "The number is " . $i . "<br>";
    $i++;
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5


do...while statement

The do...while statement will execute the code at least once, then check the condition. As long as the condition is true, the loop will repeat.

Syntax

do
{
    要执行的代码;
}
while (条件);

Examples

The following example first sets a variableito the value 1 ($i=1;).

Then, it starts the do...while loop. The loop increments the variableiby 1, then outputs it. The condition is checked first (iis less than or equal to 5), as long asiis 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:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

The for loop and foreach loop will be explained in the next chapter.

Other extensions