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

"; } ?>

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:
"; } ?>

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

'; } ?>

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

 '小明', 'name2' => '小奇', ); foreach($data as $key => $value){ echo $key . '-------' . $value . '
'; } ?>

Program running result:

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



##

Continuing Learning
||
"; } ?>
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!