PHP flow contro...LOGIN

PHP flow control for loop control statement

Student Wang traveled back and forth between Beijing and Dalian repeatedly, and recorded the number of round trips in his notebook. There is another implementation in PHP that can achieve the same counting.

The for loop is a counting loop in PHP, and its syntax is quite variable. This is a knowledge point that must be mastered.

for (表达示1; 表达示2; 表达示3){
        需要执行的代码段
}
  • Expression 1 is an initialization assignment, and multiple codes can be assigned at the same time.
  • Expression 2 is evaluated before each loop starts. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.
  • Expression 3 is evaluated after each loop.

Let’s write a simple example and see:

<?php
for ($i = 1; $i <= 10; $i++) {
    echo '分手后第'.$i.'年,我全都忘了你的样子<br />';
}
?>

In other words, let’s try to judge multiple conditions:

<?php
    for($i=0,$j=10;$i<$j;$i++,$j--){    
    echo $i.'---------'.$j.'<br />';
    }
?>

We use for Let’s type the 9*9 multiplication table in a loop. The demonstration effect is as follows:
2015-08-08/55c5b92de2c2b

Remember during the analysis and thinking process: the code is output horizontally

<?php

//99乘法口诀表从1开始,所以声明一个变量$i = 1,让$i小于10,也就是最大值为9
for($i = 1 ; $i < 10 ; $i++ ){
        //1x1=1,2x2等于4,所以第二次循环的最大值为$i的值,因此$j=1, $j在循环自加的过程当中,只能够小于等于$i

    for($j=1;$j<=$i;$j++){
                //  1 x 2 = 2   2 x 2 = 4啦
        echo $j . 'x' . $i . '=' .($i*$j) . '&nbsp;&nbsp;&nbsp;';
    }
    echo '<br />';

}

Let's try break, exit and continue to control the 9*9 multiplication table.

##exitBefore exit We have talked about stopping subsequent execution from the current locationbreakI have encountered it before, jumping out of the loop or structure to execute subsequent codecontinueJump out of this loop and continue the next loop
StatementFunction
Let’s demonstrate break and continue:

<?php
for ($i = 1; $i <= 10; $i++) {

    if($i == 4){
            //待会儿换成continue试试
            
            break;
    }

    echo '分手后第'.$i.'年,我全都忘了你的样子<br />';
}
?>

$i is equal to 4, the effect of break is as follows:


Note: No longer executed after the 4th point in the above figure 2015-08-08/55c5bba280e19

$i is equal to 4, the effect of continue is as follows:


Note : The 4th one in the picture above is lost, and then the 2015-08-08/55c5bbcd4fb1b


job is continued from the 5th year:

Use a single-layer for loop to control the table that changes color on alternate rows

Use the double-layer loop of for to control the color-changing table of alternate rows
Write 99 multiplication tables silently, and experiment with continue and break at the positions of $i and $j in the middle;

Next Section
<?php for ($i = 1; $i <= 10; $i++) { if($i == 4){ //待会儿换成continue试试 break; } echo '分手后第'.$i.'年,我全都忘了你的样子<br />'; } ?>
submitReset Code
ChapterCourseware