Κύκλος For στο PHP
- Previous Page PHP While Loop
- Next Page Συνάρτησεις PHP
PHP για την εκτέλεση κώδικα块的指定次数。
Κύκλος For στο PHP
If you have already determined the number of times the script runs in advance, 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 iteration of the loop. 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 "Number is: $x <br>"; } ?>
PHP foreach Loop
The foreach loop is only applicable to arrays and is used to iterate over each key/value pair in the array.
Syntax
foreach ($array as $value) { code to be executed; }
With 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 will output 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