Home >Backend Development >PHP Tutorial >Usage of for(), while(), and foreach() in loops in php_PHP tutorial
This article introduces the use of the most basic loop statements, including the most basic statements such as for(), while(), foreach() do while in php.
while loop
The while loop is the simplest loop in PHP, its basic format is:
The code is as follows | Copy code | ||||||||
while (expr){
} //orwhile (expr): Statement
|
Example:
The code is as follows | Copy code |
$i = 1; while ($i | |
代码如下 | 复制代码 |
do { statement }while (expr) |
$i++;
}代码如下 | 复制代码 |
$i = 1; do { echo $i; $i++; } while ($i ?> |
This example loops out 1 to 10.
do-while loop
代码如下 | 复制代码 |
for (expr1; expr2; expr3){ statement } |
The do-while loop has only one syntax:
The code is as follows | Copy code | ||||
do {
|
The code is as follows | Copy code |
$i = 1; do { echo $i; $i++; } while ($i ?> |
The code is as follows | Copy code |
for (expr1; expr2; expr3){ Statement } |
The code is as follows | Copy code |
for ($i = 1; $i echo $i; } ?> |
Grammar interpretation
The first expression (expr1) is evaluated unconditionally once before the loop starts
expr2 is evaluated before each loop 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
Every expression can be null. If expr2 is empty, the loop will continue indefinitely, but the loop can be ended by break:
The code is as follows
|
Copy code
|
||||
for ($i = 1; ; $i++ ) { If ($i > 10) { | break;
?>
http://www.bkjia.com/PHPjc/629220.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629220.htmlTechArticleThis article introduces the use of the most basic loop statements, including for(), while(), foreach() do while are the most basic statements. while loop while loop is the simplest loop in PHP...