Latest web development tutorials

PHP While loop

Loop executes a block of code a specified number of times, or when a specified condition is true loop code block is executed.


PHP loop

When you write code, you often need to make the same block of code to run over and over again. We can use looping statements in your code to accomplish this task.

In PHP, we provide the following loop:

  • while - as long as the specified condition is satisfied, the loop code block is executed
  • do ... while - first executes a block of code, and then repeat the cycle when the specified conditions are met
  • for - times the loop executes a block of code specified
  • foreach - according to each element in the array to loop code block

while loop

while loop repeats a block of code until a specified condition is not satisfied.

grammar

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

Examples

The following examples set the first value of the variablei is1 ($ i = 1;) .

Then, as long asiis less than or equal to 5, while loop will continue to run. Each time you runloop,it is incremented 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

do ... while statement will execute the code at least once, and then checks the condition, as long as the condition is true, it will repeat the cycle.

grammar

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

Examples

The following examples set the first value of the variablei is1 ($ i = 1;) .

Then, start do ... while loop. The value of the loop variableiis incremented by one, and then output. Check the condition(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

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