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 PHPThe second year of learning PHPThe third year of learning PHP
Writing it another way, let’s try to judge multiple conditions:
Learning PHP Year 4
"; } ?>
Program running result:
0-- ------81--------72--------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 characterRun 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
##