|
| HOW TO USE for LOOPS IN PHP
A for loop is used to repeatedly execute a block of code. It can be set to repeat a certain amount of times or until a certain condition is met.
The general format is as follows:
for (startValue; endCondition; increment)
{
code to be executed;
}
Example:
We want to echo the numbers from 1 to 5.
for ($i=1; $i <= 5; $i++)
{
echo $i."<br>";
}
This for loop sets up a variable $i and gives it a value of 1 to start. We then set the condition part of the for loop to say that the loop must stop as soon as $i is less than or equal to 5. The $i++ increments the value of $i by 1 each time the loop runs. So $i changes in value from 1 to 2 to 3 to 4 and lastly to 5 after which the loop ends. The echo statement echos the possible $i values as the loop ran. So, therefore the above code will output:
1
2
3
4
5
|
|