PHP Loop-While Loop
Loop executes the number of times specified by the code block, or the loop executes the code block when the specified condition is true.
PHP Loops
When you write code, you often need to have the same code block run repeatedly again and again. We can use loop statements in our code to accomplish this task.
In PHP, the following looping statements are provided:
- While-loops through code blocks as long as the specified condition is true
- Do...while -Executes the code block first, and then repeats the loop when the specified condition is set
- for-loop execution code block specified number of times
- foreach -loops a block of code based on each element in the array
While loop
The while loop executes the code block repeatedly until the specified condition is not true.
Grammar
while (condition) { the code to execute;}
Instance
The following instance first sets the value of the variable i to 1 ($i = 1;).
Then, as long as I is less than or equal to the 5,while loop will continue to run. Each time the loop is run,i increments by 1:
PHP $i=1; while ($i<=5) { echo$i . "<br>"; $i+ +;}? ></body>
Output:
number is 1 number are 2 number is 3 number is 4 number is 5
Do...while statementsThe Do...while statement executes the code at least once and then checks the condition, repeating the loop as long as the condition is true.
Grammar Do { the code to execute;} while (conditions);
InstanceThe following instance first sets the value of the variable i to 1 ($i = 1;).
Then, start the Do...while loop. The loop increments the value of the variable i by 1 and then outputs. 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:
PHP $i=1; Do { $i++ ; Echo $i . "<br>";} while ($i<=5);? ></body>
Output:
number is 2 number are 3 number is 4 number is 5 number is 6
The For loop and the Foreach loop are explained in the next chapter.
PHP Quick Start learning -13 (PHP loop-while loop)