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){ 需要执行的代码段 }
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:
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) . ' '; } echo '<br />'; }
Let's try break, exit and continue to control the 9*9 multiplication table.
Statement | Function |
---|---|
Before exit We have talked about stopping subsequent execution from the current location | |
I have encountered it before, jumping out of the loop or structure to execute subsequent code | |
Jump out of this loop and continue the next loop |
<?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
Note : The 4th one in the picture above is lost, and then the
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;