PHP Loops
When you write code, you often need to run the same block of code repeatedly. Instead of adding several almost equal lines of code to the script, we can use loops to perform such tasks.
In PHP, we have the following looping statements:
While-loop code block whenever the specified condition is true
Do.bjrongjinhuiyin. While-executes the code block first, and then repeats the loop whenever the condition is specified as True
For-loop code block specified number of times
foreach-iterates through each element in the array and loops the block of code
PHP while loop
As long as the condition is true, the while loop executes the code block.
Grammar
while (condition is true) {
The code to execute;
}
The example above first sets the variable $x to 1 ($x =1). The while loop is then executed as long as the $x is less than or equal to 5. Each time the loop runs, the $x increments by 1:
Instance
<?php
$x = 1;
while ($x <=5) {
echo "This number is: $x <br>";
$x + +;
}
?>
Running an instance
PHP Do...while Loops
The Do...while Loop executes the code block first, then checks the condition and repeats the loop if the specified condition is true.
Grammar
do {
The code to execute;
} while (condition is true);
The following example first sets the variable $x to 1 ($x =1). Then, the Do While loop outputs a string, and then increments the variable $x by 1. The condition is then checked ($x is less than or equal to 5). As long as the $x is less than or equal to 5, the loop will continue to run:
Instance
<?php
$x = 1;
do {
echo "This number is: $x <br>";
$x + +;
} while ($x <=5);
?>
Running an instance
Note that the Do While loop tests the condition only after executing the statement inside the loop. This means that the Do While loop executes at least one statement at a time, even if the condition test fails the first time.
The following example sets the $x to 6 and then runs the loop, followed by a check of the condition:
Instance
<?php
$x = 6;
do {
echo "This number is: $x <br>";
$x + +;
} while ($x <=5);
?>
PHP while loop