PHP for loop
PHP for loop executes the code block a specified number of times.
PHP for loop
If you have determined in advance the number of times the script will run, you can use a for loop.
Syntax
for (init counter; test counter; increment counter) { code to be executed; }
Parameters:
· init counter: Initialize the value of the loop counter
· Test counter:: Evaluate each loop iteration. If the value is TRUE, continue looping. If its value is FALSE, the loop ends.
· increment counter: Increase the value of the loop counter
The following example shows the number from 0 to 10:
Example
<?php for ($x=0; $x<=10; $x++) { echo "数字是:$x <br>"; } ?>
PHP foreach loop
The foreach loop only works on arrays and is used to iterate through each key/value pair in the array.
Syntax
foreach ($array as $value) { code to be executed; }
Every time a loop iteration is performed, the value of the current array element will be assigned to the $value variable, and the array pointer will move one by one until the last array element is reached.
The following example demonstrates a loop that will output the values of the given array ($colors):
Example
<?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
for (expression indicates 1; expression indicates 2; expression indicates 3) {
The code segment that needs to be executed
#}
· Expressive 1 is initialized assignment and can assign multiple code 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.
· & LT;? PHP
· For ($ i = 1; $ i & lt; = 10; $ i ++) {
· Echo 'This is the first'. $ I. ' <br />';
· }
· -------------------------------------------------- -------------------------------------------------- -------------------
Use a for loop to create a 9*9 multiplication table. ##//99 The multiplication table starts from 1, so declare a variable $i = 1 and make $i less than 10, that is, the maximum value is 9
<?PHP for($i=0,$j=10;$i<$j;$i++,$j--){ echo $i.'---------'.$j.'<br />'; } ?>foreach loop
## The #foreach loop is used to traverse the array and can be used later when operating on the array.
Syntax
foreach ($array as $value)
{ Code to be executed;
}
Every time you loop, the value of the current array element will be assigned to the $value variable (the array pointer will move one by one), and when you loop next time, you will see the next value in the array.
<?php ? >Next Section