PHP complete se...login
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP While Loop



Loop through a block of code a specified number of times, or when a specified condition is true.


PHP Loops

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

In PHP, the following loop statements are provided:

  • while - As long as the specified condition is true, the code block will be executed in a loop

  • do...while - First execute the block of code once, then repeat the loop when the specified condition is true

  • for - Loop through a block of code a specified number of times

  • foreach - Loop through a block of code for each element in the array


php What does while loop mean?

while loop

The while loop will repeatedly execute a block of code until the specified condition is not true.

Syntax

while (Condition)
{
Code to be executed;
}

Example

In the following php while loop example, first set the value of variable i to 1 ($i=1;).

Then, the while loop will continue to run as long as i is less than or equal to 5. Each time the loop runs, i 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 executes the code at least once, then checks the condition, and repeats the loop as long as the condition is true.

Grammar

do
{
Code to be executed;
}
while (condition);

Example

below In the example of php dowhile loop statement, first set the value of variable i to 1 ($i=1;).

Then, start the do...while loop. The loop increments the value of variable i by 1 and then outputs it. First check the condition (i is less than or equal to 5), 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:

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

Related practical tutorial recommendations: "while loop"

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

php.cn