PHP For Loops
- Previous Page PHP While Loop
- Next Page PHP Functions
PHP for loop executes the code block for the specified number of times.
PHP For Loops
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 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 "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 Functions