PHP while loops

If we wanted to run some PHP code multiple times, we could write the same code out multiple times. Alternatively we could use a loop construct to run the same bit of code over and over again.

A while loop is the simplest form of loop in PHP, it will execute the PHP code inside the loop as long as the expression evaluates to true. The syntax is as follows:

<?php
while(expression)
{
    
// do something
}
?>

The expression is checked at the start of each loop, if it is false then the code in the loop will not execute and PHP will skip that section of code and continue from the end of loop. If it is true PHP will execute the statements in the loop and check the expression once again.

A simple example

Printing the numbers 1 to 5 is an easy way to demonstrate a while loop. Here is the PHP code:

<?php
$number 
1;
while(
$number <= 5)
{
    echo 
$number;
    
$number++;
}
?>

Let's go through this line by line:

Line #1 the variable $number is set to 1
Line #2 a while loop is started - PHP checks to see if $number is less than or equal to 5. It is and so the code in the while loop is executed
Line #3 the value of the variable $number is outputted
Line #4 the value of the variable $number is increased by 1
Line #5 a while loop ends, PHP returns to the beginning and checks the expression again.

In this example the loop continues until $number is set to 6, this causes the expression of the while loop to become false and so the code in the loop is no longer executed. The code above will output:

12345

And that is the basics of PHP while loops!

Alternative syntax

While loops can also be written in an alternate syntax, this code does the exact same thing as the snippet above:

<?php
$number 
1;
while(
$number <= 5):
    echo 
$number;
    
$number++;
endwhile;
?>

A "realworld" example

You're unlikely to ever want to print just a list of numbers in PHP code, so in this section we'll look at a real world example of a while loop. Suppose you run an online shop which sells products and you want to offer customers discounts if they buy in bulk. You could manually create a table and calculate the discount for each quantity, but what happens later if you decide to raise or lower your prices? You're going to have to do all the calculations again. This process can be easily carried out using a while loop. Take the following HTML and PHP code:

<table border="1">
    <tr>
        <th>Quantity</th>
        <th>Usual price</th>
        <th>Discounted price</th>
        <th>You save</th>
    </tr>
    
    <?php

    $product_cost 
10;
    
$discount 2;

    
$minimum_purchase 10;
    
$maximum_purchase 100;



    
$quantity $minimum_purchase;
    while(
$quantity <= $maximum_purchase)
    {
        
        
$you_save $discount $quantity;
        
$usual_price $product_cost $quantity;
        
$discounted_price $usual_price $you_save;

        echo 
"<tr>
            <td>{$quantity}</td>
            <td>£{$usual_price}</td>
            <td>£{$discounted_price}</td>
            <td>£{$you_save}</td>
              </tr>"
;

        
$quantity += 10;
    }

    
?>

</table> 

Woah! So what's happening here? Well the first bit of this code is just HTML and starts a table. Then we start with our PHP code and set 4 variables: $product_cost - the cost a single product, $discount - the discount for every 10 products bought, $minimum_purchase - the minimum amount of products needed to purchase to get a bulk discount and lastly $maximum_purchase - the largest quantity of the product a customer can order.

We now start our processing. First of all we setup a new variable called $quantity and set this to the value of $minimum_purchase. This is outside the while loop so will only be executed once. We then start the while loop which checks to see if the current value of $quantity is less than or equal to the maximum purchase variable, if so we make some calculations. $you_save calculates how much a customer will save if they buy $quanity of products at a discount of $discount, $usual_price calculates how much it would usually cost for $quantity of products at $product_cost price and lastly $discounted_price calculates how much it will cost the customer to purchase the $quanity of products with the $discount applied.

All these values are then outputted in a HTML table row. Just before the end of the loop we add 10 to the current quantity. The while loop is finsihed, so it returns to the start and once again compares the value of $quantity against $maximum_purchase and executes the code once more if $quanity is less than or equal to it.

The above code will output a table like this:

Quantity Usual price Discounted price You save
10 £100 £80 £20
20 £200 £160 £40
30 £300 £240 £60
40 £400 £320 £80
50 £500 £400 £100
60 £600 £480 £120
70 £700 £560 £140
80 £800 £640 £160
90 £900 £720 £180
100 £1000 £800 £200

Now not only don't you or your customers have to waste time with calculating and apply discounts you don't need to worry about changing your prices!

And this concludes this tutorial on while loops, thank you for reading.