The usage of loop for (), while (), and foreach () in php. This article introduces the usage of the most basic loop statements, including the for (), while (), and foreach () dowhile statements in php. The while loop is the simplest example in PHP. This article introduces the usage of the most basic loop statements, including for (), while (), and foreach () in php () do while are the most basic statements.
While loop
While loop is the simplest loop in PHP. its basic format is:
| The code is as follows: |
|
While (expr ){
Statement
}
// Or
While (expr ):
Statement
Endwhile;
|
This syntax indicates that as long as the expr expression is TRUE, statement is executed until the expr is FALSE, and statement indicates the action or logic to be executed.
Example:
| The code is as follows: |
|
$ I = 1;
While ($ I <= 10 ){
Echo $ I;
$ I ++;
}
?>
|
In this example, 1 to 10 are output cyclically.
Do-while loop
The do-while loop is very similar to the while loop. The difference is that the do-while loop must be executed once, while the while loop may not perform any operation when the expression is invalid.
The do-while loop has only one syntax:
| The code is as follows: |
|
Do {
Statement
} While (expr)
|
Example:
| The code is as follows: |
|
$ I = 1;
Do {
Echo $ I;
$ I ++;
} While ($ I <= 10 );
?>
|
This example also outputs 1 to 10
For loop
A for loop is a more complex loop in PHP. Its syntax is as follows:
| The code is as follows: |
|
For (expr1; expr2; expr3 ){
Statement
}
|
The following example still outputs 1 to 10:
| The code is as follows: |
|
For ($ I = 1; $ I <= 10; $ I ++ ){
Echo $ I;
}
?>
|
Grammar explanation
The first expression (expr1) is unconditionally evaluated once before the loop starts.
Expr2 evaluates the value before each loop starts. if the value is TRUE, the loop continues and runs the nested loop statement. if the value is FALSE, the loop ends.
Expr3 is evaluated (executed) after each loop)
Each expression can be empty. If expr2 is null, the loop is infinite, but the loop can be ended through break:
| The code is as follows: |
|
For ($ I = 1; $ I ++ ){
If ($ I> 10 ){
Break;
}
Echo $ I;
}
?>
|
Prompt
When using a loop statement, we usually need to be careful not to create an infinite loop and cause the program to "zombie". In addition, we also need to pay attention to the loop conditions (loop judgment expressions) to ensure that the loop results are correct.
Explain (), while (), foreach () do while are the most basic statements. While loop is the simplest cycle in PHP...