While loop
While loop is the simplest loop in PHP. Its basic format is:
The code is as follows: |
Copy code |
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: |
Copy code |
<? Php $ 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: |
Copy code |
Do { Statement } While (expr)
|
Example:
The code is as follows: |
Copy code |
<? Php $ 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: |
Copy code |
For (expr1; expr2; expr3 ){ Statement }
|
The following example still outputs 1 to 10:
The code is as follows: |
Copy code |
<? Php 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: <? Php
The code is as follows: |
Copy code |
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.