This article describes the use of the most basic looping statements, including the most basic statements in PHP for the for (), while (), and foreach () do.
While loop
The while loop is the simplest loop in PHP, and its basic format is:
The code is as follows |
Copy Code |
while (expr) { Statement } Or while (expr): Statement Endwhile;
|
This syntax means that as long as the expr expression is true, the statement is executed until expr is false, and statement represents the action or logic to be executed.
Example:
The code is as follows |
Copy Code |
$i = 1; while ($i <= 10) { echo $i; $i + +; } ?>
|
The example loops out 1 to 10.
Do-while Cycle
The Do-while loop is very similar to the while loop, except that the do-while guarantees that it must be executed once, while the while is not possible when the expression is not true.
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 |
$i = 1; do { echo $i; $i + +; } while ($i <= 10); ?>
|
The example is also output 1 to 10
For loop
The For loop is a more complex loop in PHP with the following syntax:
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 |
for ($i = 1; $i <=; $i + +) { echo $i; } ?>
|
Grammatical interpretation
The first expression (EXPR1) is evaluated unconditionally once before the loop begins
The EXPR2 evaluates before each cycle, and if TRUE, resumes looping, executes a nested loop statement, or terminates the loop if the value is FALSE.
EXPR3 evaluated after each cycle (execution)
Each expression can be empty. If the expr2 is empty, it will loop indefinitely, but the loop can be ended by a break:
The code is as follows |
Copy Code |
for ($i = 1;; $i + +) { if ($i > 10) { Break } echo $i; } ?>
|
Tips
In the use of circular statements, we usually have to pay attention to not infinite loop and cause the program "zombie", in addition to pay attention to the loop condition (circular judgment expression), to ensure that the loop results are correct.
http://www.bkjia.com/PHPjc/629220.html www.bkjia.com true http://www.bkjia.com/PHPjc/629220.html techarticle This article describes the use of the most basic looping statements, including the most basic statements in PHP for the for (), while (), and foreach () do. The while loop is the simplest in PHP to follow ...