دائرة for في PHP
- Previous Page PHP While Loop
- Next Page وظائف PHP
PHP for 循环执行代码块指定的次数。
دائرة for في PHP
If you have already determined the number of times the script should run, you can use the 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 the loop. If its value is FALSE, the loop ends.
- increment counter: increase the value of the loop counter
The following example shows numbers from 0 to 10:
Example
<?php for ($x=0; $x<=10; $x++) { echo "The number is: $x <br>"; } ?>
PHP foreach Loop
The foreach loop is only applicable to arrays and is used to traverse each key/value pair in the array.
Syntax
foreach ($array as $value) { code to be executed; }
During each iteration of the loop, the value of the current array element is assigned to the $value variable, and the array pointer moves sequentially until it reaches the last array element.
The following example demonstrates a loop that outputs the values of the given array ($colors):
Example
<?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
In the following chapters, you will learn more about arrays.
- Previous Page PHP While Loop
- Next Page وظائف PHP