PHP Loops
When you write code, you often need to run the same block of code over and over again. Instead of adding several nearly equal lines of code to the script, we can use a loop to perform such a task.
In PHP, we have the following loop statement:
· while - As long as the specified condition is true, the loop code block
· do...while - execute the code block once first, and then repeat the loop as long as the specified condition is true
· for - loop the code block a specified number of times
· foreach - traverse the array each element in and loop the code block
##PHP while loop
while is a Boolean loop. If the value of while (Boolean judgment) is true, the code enclosed in curly brackets will be executed. If it is false, stop and execute the subsequent code.
grammar
while (condition is true){
//Executed code;}
Example
The following example first sets the variable $x is 1 ($x=1). The while loop is then executed as long as $x is less than or equal to 5. Each time the loop runs, $x will increase by 1:
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $x=1; while($x<=5){ echo "这个数是---".$x ."<br/>"; $x++; } ?>
Look at the results of the program:
This number is---1This The number is---2
The number is---3
The number is---4
The number is---5
Note: Do not write an infinite loop (a loop without exit conditions) like the following program
<?phpwhile condition is one, which is always true, so it will keep looping, which is a loop, causing the page to crashwhie(1){
echo 1111.'<br / >';
}?>
##PHP do...while Loop
do...The difference between while and while is that their values are checked at different times.
do-while Regardless of whether the while judgment is true, the code block loop statement is executed once, and it is guaranteed to be executed once (the truth value of the expression is checked after each loop).
However, our while loop above will check the Boolean judgment area and execute it if it is true. If not established, it will not be executed.Syntax ##do{ //Executed code ; }while (condition is true); Example <?php
header("Content-type:text/html;charset=utf-8"); //设置编码
$x=1;
do {
echo "这个数字是:$x <br>";
$x++;
} while ($x<=5);
?>
Let's take a look
<?php
header("Content-type:text/html;charset=utf-8"); //设置编码
$x=6;
do {
echo "这个数字是:$x <br>";
$x++;
} while ($x<=5);
?>
The above example fully illustrates that even if the conditions of the do...while loop are not satisfied, the code will Execute it once
The for loop and foreach loop will be explained in the next chapter.