Use a for loop to execute a block of code a specified number of times.
Syntax:
for (init; condition; increment) { code to be executed; }
The for loop is based on a counter.
- init is the counter’s initial value
- condition indicates when to stop the loop
- increment indicates how much to increase or decrease the counter, each time around the loop
Example, loop numbers one through four:
<?php for ($i=1; $i<=4; $i++) { print 'Number ' . $i . '<br />'; } ?>
In the above example:
- $i is a variable (the loop counter)
- Initial counter value is one
- Condition: continue loop if counter is less than or equal to four (note the <= operator)
- Increment counter plus one after each time through the loop (note the ++ operator)