Detailed explanation of PHP loop statement

Loop structure
1. while loop
while(expression)
{
loop body;//Iteratively execute until the expression is false
}

代码:
$index = 1;
while ($index<5)
{
print "Number is {$index}
";
$index++;
}
print "Done";
运行结果:
Number is 1
Number is 2
Number is 3
Number is 4
Done

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 );
print "Done";
Running result:
Number is 1
Done
Do While loop statement is different from while, the difference is that do while will execute first regardless of whether the condition is true, while while must be true before executing once .

3. For loop
According to different loop conditions, there are two types of loops
: one: counting loop (usually using for) and the
other: conditional loop (usually using while do-while)
for (expr1; expr2; expr3) {
statement
}
where expr1 is the initial value of the condition. expr2 is the condition for judgment, usually using logical operators
as the condition for judgment. expr3 is the part to be executed after the statement is executed. It is used to change the condition for the next loop judgment, such as adding one.. and so on. The 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 "don't dare in the future" written with a for loop, which can be compared with a while loop.
<?php
for ($i=1; $i<=10; $i++) {
echo "$i. I won't dare to
n";
}
?>Running result:

  1. no longer
  2. no longer
  3. no longer
  4. no longer
  5. no longer
  6. no longer
  7. no longer
  8. no longer
  9. no longer
  10. no longer

Fourth, foreach loop The
foreach statement is used to loop through the array. Each time through the loop, 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:
<?php
$ arr=array("one", "two", "three");

foreach ($arr as $value)
{
echo "Value: " . $value . "
";
}
?> Operation result:
Value: one
Value: two
Value: three
The above are four kinds of loops in PHP, which can be selected according to different conditions Use the corresponding loop

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324840879&siteId=291194637