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.
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.
The above code results in:
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.
The above code results in:
Strawberries
Blackberries