PHP while loop method with syntax and example


PHP WHILE LOOP METHOD

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 OF PHP WHILE LOOP


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

EXAMPLE OF PHP WHILE LOOP

$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!";

RESULT OF THIS EXAMPLE

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!