Loops are very important in PHP code when you’re trying to execute a block of code several times or trying to move through an array.

The first type of loop we will discuss is the while loop. A while loop will run until the condition is no longer met. Here is an example of a while loop:

php:
<?php

//start off by setting a counter.
$counter = 0;

while($counter < 5) {
echo 'counter = ' . $counter . "<br />";

//increment the counter by one.
$counter++;
}

//OUTPUT:
//counter = 0
//counter = 1
//counter = 2
//counter = 3
//counter = 4
?>

As you can see, the loop will continue to execute as long as the counter is less than 5. Always remember to increment your counter in your loop. If you forget to do this your loop will never stop running and your script will crash.

The next type of loop we’ll discuss is a do…while loop. A do…while loop works like thet while loop does, except the condition is not tested until the loop has been run at least once. This means the loop will always run at least once no matter what the condition is. Here is what a do…while loop looks like:

php:
<?php
$counter=0;
do{
$counter++;
echo "counter =" . $counter . "<br />";
} while ($counter<5);

//OUTPUT:
//counter = 1
//counter = 2
//counter = 3
//counter = 4
//counter = 5
?>

The third type of loop is a for loop. A for loop works the same way as a while loop, except it keeps track of incrementing the counter for you. Here is a basic example of a for loop:

php:
<?php
//set the max value
$maxValue = 5;

for($x=0; $x<$maxValue; $x++)
{
echo 'x = ' . $x . '<br/>';
}

//OUTPUT:
//x = 0
//x = 1
//x = 2
//x = 3
//x = 4
?>

This is also a good way to loop through an array that has sequential index values. Here is an example of how that would work:

php:
<?php
//create an array.
$newArray[0] = "Bob";
$newArray[1] = "Joe";
$newArray[2] = "Sally";
$newArray[3] = "Mary";

for($x = 0; $x < count($newArray); $x++)
{
echo 'Hello ' . $newArray[$x] . '<br />';
}

//OUTPUT:
//Hello Bob
//Hello Joe
//Hello Sally
//Hello Mary

?>

In the previous example we do a few new things. The first is the use of count(). Count will find the total number of items in an array. So we’re telling the loop to continue executing while $x is less than the number of items in the $newArray array. The second thing we’re doing is using $x to find the value in $newArray. $newArray[$x] will grab the value associated with the index of $x.

A foreach loop is another great way to loop thorugh an array and find its values. Here is what a foreach loop looks like:

php:
<?php
$weekendArray=array("Friday", "Saturday", "Sunday");

foreach ($weekendArray as $value)
{
echo "Value: " . $value . "<br />";
}

//OUTPUT:
//Value: Friday
//Value: Saturday
//Value: Sunday
?>

Loops are a great way to enhance your PHP scripts. Just play around with them and you will soon learn that they are very easy to create and manage.