Basics of PHP – While & For
June 1, 2010
During the tutorial Basics of PHP – MySql Query (Select) We used the ‘while’ loop, but we didn’t really talk about what it does that much. Essentially ’while’ and ‘for’ allow us to do something over and over again, quickly and easily. First let’s look at this ‘while’ example.
<?php
$counter = 1;
while($counter <= 10) {
echo 'Number ' . $counter . '<br />';
$counter ++;
}
?>
In a way ‘while’ and ‘for’ are similar to ‘if’, they are all looking for a condition to be true. In this example we have first set the $counter variable to 1, then we run our ‘while’ loop. ‘While’ continues to execute the code in between the curly brackets provided the $counter variable is less than or equal to 10. Still following? Provided $counter is less than or equal to 10 PHP will display the text “Number ” and then the $counter variable (which will be a number between 1 and 10), and then starts a new line. The $counter variable is then incremented by one, so if the counter was 1 it will not be 2, if it was 2 it will now be 3 ect. Then the ‘while’ loop runs again, checking if $counter is still less than or equal to 10, eventually (after 10 times to be exact) the $counter variable will reach 10 and the ‘while’ loop will not be able to run again. PHP will output this to the browser…
Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 Number 7 Number 8 Number 9 Number 10
The ‘for’ loop is exactly like the ‘while’ loop except it simplifies the process of assigning and incrementing a counter, here is an example of a ‘for’ loop which will output the same as the previous ‘while’ loop.
<?php
for($counter = 1; $counter <= 10; $counter ++) {
echo 'Number ' . $counter . '<br />';
}
?> You will notice that all the counter settings are set as parameters inside ‘for’, parameters in ‘for’ are separated by a semicolon. The first parameter sets the variable name to be used as a counter as well as it’s starting value, the second parameter sets the condition that ‘for’ should continue to run under and the third tells ‘for’ what to do after the loop has ran, in this case (and in most) it increments the counter. You will also notice that as the increment is set as a parameter you don’t need to set the counter to be incremented inside the curly brackets.