your image

PHP While Loops

quackit
Related Topic
:- PHP programming skills

PHP While Loops

 

As with most programming languages, PHP supports the "while" loop.

PHP "while" loops allow you to execute the same piece of code continuously while a certain condition is true. Once the condition becomes false, the program will break out of the loop and continue processing the rest of the page.

Syntax

 

while (condition)
{
 Code to be executed while the condition is true;
}

Example

This example executes the same piece of code while the "sharePrice" variable is less than or equal to 10. With each iteration through the loop, we increment the value of $sharePrice by 1. This means the value of $sharePrice will eventually become greater than 10, which will result in the end of the loop, and the rest of the page will be processed.

 

 
$sharePrice = 1;
while ($sharePrice <= 10)
{
 echo "The share price is " . $sharePrice . ". Don't sell yet. <br>";
 $sharePrice = $sharePrice + 1;
}
echo "The share price is " . $sharePrice . ". SELL NOW!";

The above code results in:

The share price is $1. Don't sell yet.
The share price is $2. Don't sell yet.
The share price is $3. Don't sell yet.
The share price is $4. Don't sell yet.
The share price is $5. Don't sell yet.
The share price is $6. Don't sell yet.
The share price is $7. Don't sell yet.
The share price is $8. Don't sell yet.
The share price is $9. Don't sell yet.
The share price is $10. Don't sell yet.
The share price is $11. SELL NOW!

Do/While Loops

A do/while loop is similar to a while loop. The difference is that a do/while loop executes the code at least once before checking the condition. Therefore, if the condition is false, a do/while loop will execute once. A while loop, on the other hand, won't execute the code at all if the condition is false.

Example

This example demonstrates the difference between a while loop and a do/while loop.

  • While Loop

     

     
    $sharePrice = 15;
    while ($sharePrice <= 10)
    {
     echo "The share price is " . $sharePrice . ". Don't sell yet. <br>";
     $sharePrice = $sharePrice + 1;
    }
    echo "The share price is " . $sharePrice . ". SELL NOW!";

    The above code results in:

    The share price is 15. SELL NOW!

  • Do/While Loop

     

     
    $sharePrice = 15;
    do   {
     echo "The share price is " . $sharePrice . ". Don't sell yet. <br>";
     $sharePrice = $sharePrice + 1;
    }
    while ($sharePrice <= 10);
    echo "The share price is " . $sharePrice . ". SELL NOW!";

    The above code results in:

    The share price is 15. Don't sell yet.
    The share price is 16. SELL NOW!

Comments