For loops in PHP

This video tutorial explains how to use for loops to repeat code using a counter. For loops have many uses such as processing arrays and strings but in this tutorial we will just look at how to use a for loop as a counted loop.

A for loop is made up of three parts:

  • counter – which is initialised
  • condition – a condition that must evaluate to true for the loop to run its code, and is tested in each iteration of the loop
  • increment – how much the counter increases by in each iteration of the loop

For example, a for loop may contain a counter which starts at 0, and the condition in the loop is for the loop to repeat for as long as the counter is less than 50, and the increment is 1. For loops are very useful for repeating code a specified number of times, going through all the characters in a string or elements in an array and using the loop counter to check the characters in a string or elements in an array, one by one – this can be achieved by using the counter in each iteration of the loop to represent the index of the character in a string or element in an array being accessed in each iteration of the loop.

This example would look like:

for($i = 0; $i < 50; $i++){
  // code inside the loop goes here
}

In the example above a counter called $i is used. It is quite common for these loops to use a counter called i but you can call the counter whatever you like (following the same rules as any other variable). You can place for loops within for loops. If you do that, make sure you give each loop a different name for its counter. The example above also increments the counter by 1 ($i++) in each iteration of the loop.

The video below shows the steps involved in creating and using a for loop. Watch the video below and then scroll down for the sample code.

Sample PHP code:

<?php
 for($i=10;$i > 5;$i--){
 echo("This is iteration #" . $i . "</br>");
 }
?>

PHP Manual references: