Home  >  Article  >  Backend Development  >  Detailed explanation of 'for' loop statement examples of PHP loop control statements

Detailed explanation of 'for' loop statement examples of PHP loop control statements

怪我咯
怪我咯Original
2017-04-15 09:07:234350browse

In this chapter, we will explain to you the "for" loop in the PHP loop control statement.

The for loop is a complex loop structure in PHP. It has three expressions. Grammar format is as follows:

 for (expr1; expr2; expr3){
     statement;
}

Detailed syntax:

The first one Expression expr1 is executed only once at the beginning of the loop

The second expression expr2 is executed at the beginning of each loop in the loop body. If the execution result is true, it is executed. statement, otherwise, jump out of the loop and continue execution.

The third expression expr3 is executed after each loop.

for loop statement flow control chart

Detailed explanation of for loop statement examples of PHP loop control statements

Detailed explanation of for loop statement examples of PHP loop control statementsWe can think of the for loop as a compact, A concise version of the while loop, like the following,

Code written using the while loop:

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$num = 1;
while ($num <= 5) {
    echo $num;
    $num++;
}
?>

can be changed using the for loop For the following writing method

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$num = 1;
for ($num = 1; $num <= 5; $num++) {
    echo $num;
}

?>

, the results of running the two codes are the same. Therefore, in terms of functionality, the for loop and the while loop can be regarded as equivalent

for loop example

This example uses a for loop to output a number within 5

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
for($x=1;$x<5;$x++){
    echo "学习PHP的第".$x."年"."<br/>";
}
?>

Code running results:

Detailed explanation of for loop statement examples of PHP loop control statements

The above is a simple application of the for loop. You must remember that when using a loop, you must ensure that the loop can end and there should be no infinite loop. Regarding the infinite loop, in When we talked about the "while" loop statement, we have already introduced it. If you don't understand it, you can take a look. I won’t introduce too much here. In the next section, we will talk about a special loop statement in PHP called “foreach loop”.

The above is the detailed content of Detailed explanation of 'for' loop statement examples of PHP loop control statements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn