PHP Tutorial – While Loops

The PHP language has four different kinds of conditioned loops. In this PHP tutorial we will look at the “while” loop. Loops are used to execute a block of code multiple times.

In PHP, we have the following loop statements:

  • while – loop through a block of code while a specified condition is true
  • do…while – loops through a block of code once, and then repeats the loop as long as a specified condition is true
  • for – loops through a block of code a specified number of times
  • foreach – loops through a block of code for each element in an array

Syntax


while (condition)
{
  code that will be executed;
}

while loop Example

Ok, let’s look at an example:


<html>
<body>

<?php
     $x=0;
     while($x<=5)
     {
            echo "The number is " . $x . "<br />";
            $x++;
     }
?>

</body>
</html>

First we set X to 0. Then we enter the loop with; X less or equal to 5. As long as this is true the number will be printed. At the end of the loop we increment X. The loop until X is false (has the number 6.)

So the output of our example will be:


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

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.