[php home]

Php_7: Loops

Loops are a very important part of PHP and MYSQL. While there is not much involved, it is important that you understand how and why loops work. There are two types of loops that we will look at: the For Loop and the While Loop.

For Loops:

Create and then run the following loop - save as 7_1.php.

<?php
for ($i = 0; $i < 10; $i ++) {
echo "$i <br>";
}
?>

There are three main parts to this loop.

  • setting the starting value - $i= 0 (i is referred to as the sentry variable)
  • setting a condition that will end the loop - $i < 10
  • changing or incrementing the sentry variable - $i++ (this is the same as $i = $i + 1)

This loop will run as long as the condition (being less than 10) is true. Notice that there is a semicolon after each element which means that each part could be placed on its own line. However, loops are generally all on one line.

We could do the same thing using descending numbers by using ($i--) Make sure to switch the starting and ending values.

We could also increment the returned number using ($i+=2)

While Loops:

Create and then run the following loop - you can save it on 7_1.php

<?php
$i = 1;
while ($i <=10) {
echo "$i <br>";
$i++;
}
?>

The while and for loops are very similar in their execution. As long as the condition, ($i <=10), is true, the while loop will continue.

CAUTION: You need to be careful when writing loops. Any simple mistake ( t++ instead of i++ ) will result in an endless loop because the condition will always be seen as true.

Exercise 7.1: Create the following loops:

1. use a "for loop" to return all the numbers between 0 and 100 counting by 5
2. Rewrite the loop using a "while loop"
3. Change the loop so that you count backwards from 100