PHP Loops - For...LOGIN

PHP Loops - For Loop

For Loop

The for loop is a counting loop in PHP, and its syntax is quite variable.


Grammar

for (Expression 1, Expression 2, Expression 3){

Code to be executed

}

· Expression 1 is initialization Assignment, 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.


Example

##The following example outputs a value less than 5

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

Program running results:

The first year of learning PHP

The second year of learning PHPThe third year of learning PHP
Learning PHP Year 4

Writing it another way, let’s try to judge multiple conditions:
<?php
 for($i=0,$j=8;$i<=8;$i++,$j--){
     echo $i  ."--------" .$j ."<br/>";
 }
 ?>

Program running result:

0-- ------8
1--------7

2--------6
3--------5
4 --------4
5--------3
6--------2
7--------1
8--------0


Do you still remember the multiplication formula we recited when we were children? We try to use a for loop to output it

Example

##Output the multiplication formula

<?php
 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 />';
 
 }
 ?>

Tips

:   represents a space character

Run the program and see


foreach loop

We have already used the foreach loop when we were learning arrays

Now let’s review it

Syntax

##foreach(

Array variable to be looped as [key variable=>] value variable){//Structure of loop


}

This is a fixed usage, put the array to be looped into. as is a fixed keyword

The key variable following is optional. Define a variable at will. Each time the loop is executed, the foreach syntax will take out the key and assign it to the key variable.

The value variable following is Required. Each time it loops, the value is placed in the value variable.

Example

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$data = array(
    'name1' => '小明',
    'name2' => '小奇',
);

foreach($data  as $key => $value){
    echo $key . '-------' . $value . '<br />';
}
?>

Program running result:

name1-------Xiao Ming
name2-------Xiao Qi



##Next Section

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