PHP Loops - While Loop
Loop to execute a code block a specified number of times, or while a specified condition is true.
PHP Loops
When you write code, you often need the same block of code to run repeatedly again and again. We can use loop statements in the code to accomplish this task.
PHP provides the following loop statements:
- **while** - Loop executes the code block as long as the specified condition is true
- do...while - Executes the code block once first, then repeats this loop while the specified condition holds
- **for** - Loop executes the code block a specified number of times
- **foreach** - Loop the code block according to each element in the array
while loop
The while loop will repeatedly execute the code block until the specified condition is no longer true.
Syntax
while (条件)
{
要执行的代码;
}
Example
The example below first 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 increments by 1:
";
$i++;
}
?>
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 holds, it will repeat the loop.
Syntax
do
{
要执行的代码;
}
while (条件);
Example
The example below first sets the variable i to 1 ($i=1;).
Then, start the do...while loop. The loop will set the variable i value increment by 1, then output. 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:
";
}
while ($i<=5);
?>
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.