Loop structure
1. While loop
while(表达式) { 循环体;//反复执行,直到表达式为假 }
Code:
$index = 1; while ($index<5) { print "Number is {$index} "; $index++; } print "Done";
Run result:
Number is 1
Number is 2
Number is 3
Number is 4
Done
2. do while loop
do { 循环体;//反复执行,直到表达式为假 } while(表达式)
Code:
##
do { $index++; print "Number is {$index} "; } while($index<0); print "Done";
Run result:Number is 1
Done
Do While loop statement has certain differences from while. Their difference is that do while will be executed first regardless of whether the condition is true. , and while must be true to execute once.
3. for loop
Depending on the loop conditions, there are two types Types of loops
One type: counting loop (generally use for)
Another type: conditional loop (generally use while do-while)
for (expr1; expr2; expr3) { statement }
expr1 is the initial value of the condition. expr2 is the condition for judgment, usually using logical operators.
The conditions for judgment. expr3 is the part to be executed after statement is executed. It is used to change the conditions for the next loop judgment, such as adding one, etc. And statement
is the execution part of the program that meets the conditions. If the program has only one line, the curly brackets {} can be omitted.
The following example is an example of "I won't dare to do it again" written using a for loop. It can be compared with the one using a while loop.
Run results:1. I won’t dare anymore
2 . I won’t dare anymore
3. I won’t dare anymore
4. I won’t dare anymore
5. I won’t dare anymore
4. Foreach loop
The foreach statement is used to loop through an array. Each time the loop is performed, the value of the current array element will be assigned to the value variable (the array pointer will move 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 . " "; }
Run result:Value: oneValue: twoValue: three
The above are four types of loop bodies in PHP. Select the corresponding loop body to use according to different conditions
The above is the detailed content of Analysis of PHP loop statements—while, for, foreach, do while. For more information, please follow other related articles on the PHP Chinese website!