PHP For Loops
PHP For Loops
PHP for loops allow you to execute the same piece of code for a specified number of times. Once the specified number has been reached, the program will break out of the loop and continue processing the rest of the page.
Syntax
A PHP for loop requires 3 parameters. The 1st parameter sets a counter, the 2nd parameter defines how high the counter should get before breaking from the loop, the 3rd parameter is used to increment the counter.
for (set counter, condition, increment counter)
{
Code to be executed while the counter is less than the specified count;
}
Example
We can use the same topic we used in the previous lesson on "while" loops. In fact, for loops are more suited to this type of usage than while loops.
for ($sharePrice = 1; $sharePrice <= 10; $sharePrice++)
{
echo "The share price is " . $sharePrice . ". Don't sell yet. <br>";
}
echo "The share price is " . $sharePrice . ". SELL NOW!";
The above code results in:
The share price is $1. Don't sell yet.
The share price is $2. Don't sell yet.
The share price is $3. Don't sell yet.
The share price is $4. Don't sell yet.
The share price is $5. Don't sell yet.
The share price is $6. Don't sell yet.
The share price is $7. Don't sell yet.
The share price is $8. Don't sell yet.
The share price is $9. Don't sell yet.
The share price is $10. Don't sell yet.
The share price is $11. SELL NOW!
For/Each Loops
A for/each loop allows you to loop through arrays. It will execute code continuously until it has looped through every item in the array. Once it has done that, it will continue on processing the rest of the page.
$fruit = array("Apples", "Strawberries", "Blackberries");
foreach($fruit as $value)
{
echo $value . "<br>";
}
The above code results in:
Apples
Strawberries
Blackberries