<< PHP While Loop | PHP Tutorials | PHP Foreach Loop >>

PHP For Loop

Yep, there is another loop (and another one after this :O). This one is significantly different than the while loop, as instead of a single condition in the parentheses (brackets) there are mutliple things you have to do. Here is some syntax for ya:

for (set variable; condition to do with variable; update variable) {
code to be executed
}

How to Use a For Loop

Using a for loop is not that hard. Like the example above, you set a variable, then set a condition for the variable. The next section is to update the variable (this is done with numbers). For example:

<?php
for ($x = 0; $x < 5; $x++) {
echo $x;
}
?>

This is what the end users will see:

01234

As you can see I set $x to 0, then made the condition that it must be below 5. Next I told it to add 1 to $x each time the loop starts up again.

For Loop... with candy!

So basically what we want to do is loop through the numbers 0 to 10. Say we were using the same example as I used on the while loop page, about the stars and candies. This can be done with the for loop like so:

<table border="1" cellpadding="2" cellspacing="0">
<tr>
<th>Star Count</th>
<th>Total Candy</th>
</tr>
<?php
for ($count = 0; $count <= 10; $count++) {
?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $count * 2; ?></td>
</tr>
<?php
}
?>
</table>

This is what the end users will see:

Star Count Total Candy
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20

For Loop With Arrays

Probably the most common usage of the for loop is to iterate through array values. Iteration is (as defined by this site):

A synonym for ‘repetition’, as in a loop.

Say we want to list all possible hexadecimal characters. But we don't want to count them all. There are two PHP functions named count() and sizeof() that will get the length of the array. But remember, for the for loop to work correctly, they cannot be associative arrays. Here is an example using the count() function:

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$count = count($array);
for ($x = 0; $x < $count; $x++) {
echo $array[$x];
}
?>

This is what the end users will see:

abcdef0123456789

As you can see from above, I pre-initialized the number of items in the array. This will save some processing time from the parser. You may also notice something different. The $array[$x]. As you know by now, the $array variable holds the array data, and the data can be accessed using $array[0], $array[1], $array[2] and so on... what I didn't teach you before is that you can use a variable to determine where the value is. In this case it is the $x variable that will hold the number of the current item that we are looping through. If you want to learn how to do this with associative arrays, please go on to the next lesson.

<< PHP While Loop | PHP Tutorials | PHP Foreach Loop >>