PHP for Loop
PHP for Loop
You can use a for loop if you have already determined in advance how many times the script has been run.
Grammar
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, the loop continues. If it has a value of FALSE, the loop ends.
- Increment counter: Increase the value of the loop counter
The following example shows a number from 0 to 10:
<?php for ($x =0; $x <=10; $x + +) { echo "number is: $x <br>";}?>PHP foreach Loop
The Foreach loop applies only to arrays and is used to iterate through each key/value pair in the array.
Grammar
foreach ($array as $value) { code to is executed;}
For each iteration of the loop, the value of the current array element is assigned to the $value variable, and the array pointer moves one at a time until the last array element is reached.
The following example shows a loop that outputs the value of a given array ($colors):
Instance
<?php $colors = Array ("Red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>";}? >
PHP for Loop