PHP loop statement details: while, for, foreach, dowhile. PHP loop statement explanation while, for, foreach, dowhile 1, while loop while (expression) {loop body; repeated execution until the expression is false} code: $ index1; while ($ index5) {PHP loop statement details: while, for, foreach, do while
1. while loop
While (expression)
{
Loop body; // execute repeatedly until the expression is false
}
Code:
$ Index = 1;
While ($ index <5)
{
Print "Number is {$ index }";
$ Index ++;
}
Running result:
Number is 1
Number is 2
Number is 3
Number is 4
2. do while loop
Do {
Loop body; // execute repeatedly until the expression is false
} While (expression)
Code:
Do {
$ Index ++;
Print "Number is {$ index }";
} While ($ index <0 );
Running result:
Number is 1
The Do While loop statements are different from while statements. The difference is that do while statements are executed first regardless of whether the condition is true or not, while While statements are executed only once.
3. for loop
There are two types of loops based on different cyclic conditions.
One type: counting loop (generally)
Another type: conditional loop (usually while do-while)
For (expr1; expr2; expr3 ){
Statement
}
Expr1 is the initial value of the condition. Expr2 is the condition for judgment. it is usually determined by a logical operator number (logical operators. Expr3 is the part to be executed after statement is executed. it is used to change the condition for the next loop judgment, such as adding one. While statement
For some programs that meet the conditions, if the program has only one line, you can omit braces {}.
The following example uses the for loop to write "do not dare later". you can compare it with the while loop.
For ($ I = 1; $ I <= 10; $ I ++ ){
Echo "$ I. no more
";
}
?>
Running result:
1. do not dare later
2. do not dare later
3. do not dare later
4. do not dare later
5. do not dare later
6. do not dare later
7. do not dare later
8. do not dare later
9. do not dare later
10. do not dare later
4. foreach loop
The foreach statement is used to traverse arrays cyclically. Each cycle is performed, the value of the current array element is assigned to the value variable (the array pointer is moved one by one)-and so on
Syntax:
Foreach (array as value)
{
Code to be executed;
}
Code:
$ Arr = array ("one", "two", "three ");
Foreach ($ arr as $ value)
{
Echo "Value:". $ value ."";
}
?>
Running result:
Value: one
Value: two
Value: three
The above are four types of loop bodies in PHP. select the corresponding loop bodies based on different conditions.
When while, for, foreach, do while 1, while loop while (expression) {loop body; // execute repeatedly until the expression is false} code: $ index = 1; while ($ index5 ){...