PHP Tutorial [Part 1]

Back to Main

The For Loop

The for loop is a loop that loops a specific number of times. The for loop is useful if you want to execute a set code code a certain number of times. Lets start out with an example:

<?php
for($a=1;$a<10;$a++)
{
   echo $a."<br>";
}
?>

Output:

1
2
3
4
5
6
7
8
9

This will count from 1 to 9, and now, lets explain how it works.

The code is simply for(variable;condition;action)

The variable can be anything and have it equal to any number. So $a=1; or $myvar=123; are both 100% valid.

The condition tells the script how long to keep on looping. Typically it utilizes the same variable. $a<10; will loop while $a is less than 10. Once $a equals 10, it will move on. So in our example, it will only go to 9. We could do $a<=10; and it will loop while $a is less than or equal to 10, and it would count from 1 to 10 fully.

The last section is the action the variable will take. Typically it is $a++ or $a-- or $a+=(somenumber). You can do any action. If I was to do $a+=2, the output would have been 1,3,5,7,9 because it would have added 2 to $a every loop.

The for loop is useful for displaying tables, looping through arrays, counting, or doing any number of other applications.

Next up - While Loops

Pages: 1 2 3 4 5 6