A for loop is the most complex loop structure in PHP. Its behavior is similar to that of C language.
The syntax of the for loop is:
For (expr1; expr2; expr3)
Statement
The first expression (expr1) is unconditionally evaluated once before the loop starts.
Expr2 is evaluated before each cycle starts. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.
Expr3 is evaluated (executed) after each loop ).
Each expression can be empty. If expr2 is null, it means an infinite loop (like C, PHP considers its value TRUE ). This may not be as useful as imagined, because it is often expected that the break statement is used to end the loop rather than the true value of the for expression.
Consider the following example where they all show numbers 1 to 10:
<? Php
/* Example 1 */
For ($ I = 1; $ I <= 10; $ I ){
Echo $ I;
}
/* Example 2 */
For ($ I = 1; $ I ){
If ($ I> 10 ){
Break;
}
Echo $ I;
}
/* Example 3 */
$ I = 1;
For (;;){
If ($ I> 10 ){
Break;
}
Echo $ I;
$ I;
}
/* Example 4 */
For ($ I = 1; $ I <= 10; echo $ I, $ I );
?>
Of course, the first example looks the most normal (or the fourth one), but you may find it convenient to use an empty expression in a for loop in many cases.
PHP also supports the replacement syntax of the for loop with colons.
For (expr1; expr2; expr3 ):
Statement;
...
Endfor;
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. 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.