While Loop

☰ Menu Content


Repetitive tasks are always a burden to us.

These repetitive tasks can be make easy by loop.

The idea of a loop is to do something over and over again until the task has been completed. 

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.

Here is the basic structure of a PHP while loop:

Pseudo PHP Code:
    while ( conditional statement is true)
    {
        //do this code;
    }

This isn't valid PHP code, but it displays how the while loop is structured. 

Now study the example shown below.

PHP Code:
$brush_price = 5;
$counter = 10;

echo "<table border='1' align='center'>";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";

    while ( $counter <= 100 )
    {
        echo "<tr><td>";
        echo $counter;
        echo "</td><td>";
        echo $brush_price * $counter;
        echo "</td></tr>";

        $counter = $counter + 10;
    }

echo "</table>";
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500

Wonderful isn't? 

If you change the   while($counter <= 100) to while($counter <= 1000) a 100 row table will be produced in a blink.

The loop created a new table row and its respective entries for each quantity, until our counter variable grew past the size of 100. 

When it grew past 100 our conditional statement failed and the loop stopped.

Let's see what is going on.

  1. We first made a $brush_price and $counter variable and set them equal to our desired values.
  2. The table was set up with the beginning table tag and the table headers.
  3. The while loop conditional statement was checked, and $counter (10) was indeed smaller or equal to 100.
  4. The code inside the while loop was executed, creating a new table row for the price of 10 brushes.
  5. We then added 10 to $counter to bring the value to 20.
  6. The loop started over again at step 3, until $counter grew larger than 100.
  7. After the loop had completed, we ended the table.

With proper use of loops you can complete large tasks with ease.

Note For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)