Flashy For Loops

Posted on 06. Mar, 2010 by admin in Basics


Sometimes, once is just not enough. Thankfully, in PHP we have something called loops to help us. Basically, they allow us to repeat portions of code over and over again as much as we would like. For this tutorial let’s use two examples. Let’s say you want to first print out a simple statement five times. In regular PHP code, not using loops, it would look something like this:


<?php
echo "This is a test. ";
echo "This is a test. ";
echo "This is a test. ";
echo "This is a test. ";
echo "This is a test. ";
?>

Output:

This is a test. This is a test. This is a test. This is a test. This is a test.

If we needed to print even more of this statement we would need to use even more lines of code. With a simple statement we can print out the same lines as many times as we want.


<?php
for($i = 1; $i <= 5; $i++)
{
echo "This is a test. ";
}
?>

Output:

This is a test. This is a test. This is a test. This is a test. This is a test.

Just as like if statement you put the code you want to run in-between two brackets.  For ( counting variable; conditional statement; increment counting variable). In this case $i is our variable. We do a conditional just like in an if statement. If the variable $i is less than or equal to 5, then the code in the brackets will keep running. If not it will move on past the for statement. The last one adds one to the variable every time to code is run in the loop. We can also subtract one like this $i–; If you where to do that in this statement it would cause an infinite loop! This is where the middle condition is never met and the loop keeps repeating. This is because the $i variable would go 0,-1,-2,-3, etc. and always be less than 5.

We can also easily use variables to make for statements do much more for us. See the following example:


<?php
echo "Countdown!";

for($i = 10; $i >= 0; $i--)
{
echo $i."...";
}

echo "Blast Off!";
?>

Output:

Countdown!10… 9… 8… 7… 6… 5… 4… 3… 2… 1… 0… Blast Off!

We can also print out the counter variable to produce unique results. See you in the next tutorial on while loops.