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

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.

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.