The meaning of the
while statement is very simple. It tells PHP to repeatedly execute the nested loop statement as long as the value of the while expression is TRUE. The value of the expression is checked each time the loop starts, so even if the value changes during the loop statement, the statement will not stop executing until the loop ends. Sometimes if the value of the while expression is FALSE at the beginning, the loop statement will not be executed even once.
Loop structure: Repeat an operation according to specified conditions, and pay attention to the stop conditions, otherwise an infinite loop may easily occur.
1.while loop, if the condition is met, the loop body will be executed repeatedly
whileExpression{
Loop body
}
<?php $i=0; while($i<7){ $i++; echo $i,'<br>'; }
Output: 1 2 3 4 5 6 7
2.do. ..while loop, execute once before making a judgment
do{
Execution statement
}while expression
<span style="font-size:18px;"><?php $i=7; do{ $i++; echo $i; }while($i<7);</span>
Output: 8
3.for loop
for(initial value; conditional expression; increment){
Loop body
}
<?php for($i=0;$i<10;$i++){ echo 'hello world','<br>'; }
4. Several statements related to loops
break to stop and exit , break2 and break3 respectively represent exiting the 2-layer loop and exiting the 3-layer loop
<?php $i=0; do{ $i++; echo $i; if ($i==4){ break; } }while($i<7);
Output: 1 2 3 4
continue Skip this cycle
<?php $i=0; do{ $i++; if ($i%2==0){ continue; } echo $i; }while($i<10);
Output 1 3 5 7 9
The above is the detailed content of Detailed explanation of examples of how to use PHP loop structure. For more information, please follow other related articles on the PHP Chinese website!