Sunday 21 April 2013

PHP - While Loop


PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while - loops 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.

Deleting spam email, sealing 50 envelopes, and going to work are all examples of tasks that are repeated.
The nice thing about programming is that you can avoid such repetitive tasks with a little bit of extra thinking.
Most often these repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over again until the task has been completed.
Before we show a real example of when you might need one, let's go over the structure of the PHP while loop.

1)Simple While Loop Example


The function of the while loop is to do a task over and over as long as the specified conditional statement is true.
This logical check is the same as the one that appears in a PHP if statement to determine if it is true or false.
Here is the basic structure of a PHP while loop:

Syntax:


while (condition)

  {
  code to be executed;
  }


Example:

<html>
<body>


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



</body>
</html>



Output:

The number is 1

The number is 2
The number is 3
The number is 4
The number is 5


2)The do...while Statement


The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
A "do while" loop is a slightly modified version of the while loop.
If you recall from one of the previous lessons on While Loops the conditional statement is checked comes back true then the code within the while loop is executed.
 If the conditional statement is false then the code within the loop is not executed.

Syntax:

do

  {
  code to be executed;
  }
while (condition);


Examples:

 
<html>
<body>
 
<?php
     $x=1;
     do
     {
          $x++;
          echo "The number is " . $x . "<br />";
     }
     while ($x<=5);
?>
 
</body>
</html>
 
Output:
 
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More