In this article we are going to talk about three different types of loops. These types are called a FOR loop, a WHILE loop and a FOREACH loop. While each of them does the same thing, in that they loop though a section of code over and over again until a condition is met, they all do it in a somewhat different way. By learning about all types of loops, you can choose the best type of loop for each coding situation.
The first type of loop we are going to talk about is a WHILE loop. A while loop continues to loop while a certain condition is true. It is common to use a while loop with a counter. Here is an example:
<?php
$i = 1;
while ( $i <=10 )
{
print $i . " is your number";
$i++;
}
?>
Basically what this code says is while our number (in this case $i) is less than or equal to ten, print the number. We then use the line $i++; to add one to i. This is the same as writing $i = $i +1;
Where this comes in particularly handy is if you are working with an array (or database information that has been loaded into an array). Instead of just using a number, the number is now a key, so you are able to access each entry in the array one by one. Here is an example:
<?php
$i = 0;
while ( $i <10 )
{
print $myArray[i];
$i++;
}
?>
What this is doing is printing the value held in each position of our array (in this case $myArray) at index i, which would be 0 - 9 in our example. Let's say you wanted to cycle through all of the items in the array. Well you could count the items in the array and use that as your upper end, but you don't need to. Instead you can use a FOREACH loop. Basically a FOREACH loop will execute the same section of code once for each item. Here is an example:
<?php
$myArray = array(1, 2, 3, 4, 5);
foreach ($myArray as $x)
{
print $x . " is in your array";
}
?>
Basically what is going on here is we are printing the value of the contents of each item in the array. You always write it like this: FOREACH (array as value). In our example, we use the array $myArray and the value $x. The last type of loop we are going to look at is a FOR loop. This is similar to a WHILE loop in that it continues to execute the loop until a given condition is proven to be false. When making a FOR loop you write: FOR (start; conditional; increment) and then the code to execute. Here is an example of a FOR loop:
<?php
for ($i=1; $i <= 10; $i++ )
{
print $i . " is your number ";
}
?>
This code does exactly the same thing as the first block of code did using a WHILE loop. Our variable, in this case $i, starts at 1 and continues to print it's value until the condition of it being less than or equal to 10 is no longer true. This statement would become invalid once $i hit 11, and therefor the loop would stop. As you can see there is more than one way to scoop the loop, and hopefully you can figure out which will work best for your project.

