PHP For Loops

In the previous tutorial we covered while and do while loops. Incase you missed it and you're wondering what loops are:

Loops execute a block of code while a condition is true or a specified number of times.

There are 4 different types of loops in PHP:

  • while - loops through a block of code while a condition is true
  • do while - loops through a block of code once, then again until the condition becomes false
  • for - loops through a block of code a set number of times
  • foreach - loops through a block of code for each element of an array

In this tutorial we'll be covering 2 of these different loops, for and foreach.

For

The for loop is used when you know in advance how many times the code should run.

A for loop starts with 3 expressions. Normally used like so:

for( $i = 1, $i <= 5, $i++ )
{
      print 'The number is currently ' . $i . '<br />';
}

  • The first expression sets the value of the variable.
  • The second expression is the condition the variable is checked against.
  • The third expression is what happens to the variable at the end of each loop.

The above example would show:

The number is currently 1
The number is currently 2
The number is currently 3
The number is currently 4
The number is currently 5

Foreach

The foreach loop is used to loop through values within an array.

If we go to our previous example of fruit we can do:

$fruits = array( 'apple', 'orange', 'banana' );

foreach( $fruits as $fruit )
{
      print 'I like to eat ' . $fruit . ''s <br />';
}

The above example will show:

I like to eat apples
I like to eat oranges
I like to eat bananas

We can also use a foreach loop to get the array key along with its corresponding value. If we take a basic array about a family member and say we want to display their information in a list. This would be done like so:

$thomas => array (
        'age'       =>   '18',
        'eyes'      =>   'green',
        'hair'      =>   'brown',
    ),

print '<h3>About Thomas</h3>
<ul>';

foreach( $thomas as $att => $value )
{
     print '<strong>' . $att . '</strong>: ' . $value;
}
print '</ul>';

This will produce a list displaying the following information:

age: 18
eyes: green
hair: brown

Conclusion

Loops are very useful across PHP and have different uses. We will return to While Loops when we visit MySQL (databases). As you begin to use more Arrays in your code you will find yourself using foreach loops more and more.