The for statement is the most basic statement in the loop control part of PHP (also multiple languages). The execution rules and basic usage of the for statement are not described here, see the for statement section in the PHP Manual. The syntax of PHP is defined as follows:
For (expr1; expr2; expr3)
Statement
The following describes several useful variants of the for statement.
1. Infinite loop
The first is an infinite loop (also known as an "endless loop "). The null expression is effective in syntax, so we can leave the three expressions of the for statement empty, which will produce continuous execution of the for nested statement.
<? Php
For (;;){
// Place the statements that require continuous execution
}
?>
Although some tasks use infinite loops, most Program tasks, especially PHP fields, add conditions for terminating loops when using infinite loops.
<? Php
For (;;){
// If it is 2199 AD, it will jump out of the loop
If (date ('Y') = '000000 '){
Break;
}
}
?>
2. Use an empty expression
Next we will talk about the use of the null syntax in the initialization statement expr1. The most common function of leaving expr1 blank is to complete more complex initialization.
<? Php
If (isset ($ I )){
Unset ($ I );
If (int) date ('') <2008 ){
$ I = 0;
} Else {
$ I = 1;
}
} Else {
$ I = 3;
}
For (; $ I <10; $ I ){
Echo $ I;
}
?>
In the same way, the iteration expression expr3 may also be left blank. You can also use this to write more complex iterations, such as calling different iterations based on different conditions.
The expr2 field in the for statement is an infinite loop mentioned above. Of course, you can add more complex conditions to determine when to jump out of the loop, which is not repeated here.
3. Multiple cycles
Using multiple loops to control multiple variables is also a feature that is often ignored in the for statement. In the following example, a double loop is usually used in a general task, and a triple or above loop is of little significance.
<? Php
For ($ I = 0, $ j = 10; $ I <= 10; $ I, $ j --){
Echo "$ I $ j = 10 ";
}
?>
The above code will be output:
0 10 = 10
1 9 = 10
2 8 = 10
3 7 = 10
4 6 = 10
5 5 = 10
6 4 = 10
7 3 = 10
8 2 = 10