PHP While Loop

The while loop in PHP is a fundamental control structure that repeatedly executes a block of code as long as the specified condition evaluates to true. It is especially useful when you do not know beforehand how many iterations are needed.

Tutorials dojo strip



Example: Counting Motorcycles

Here’s an example where we display the number of motorcycles a showroom can store, as long as the count remains under 6:

PHP

Note: It is essential to increment the variable within the loop to avoid an infinite loop.




The break Statement

The break keyword is used to terminate a loop prematurely, even if the condition remains true.

Example: Break at a Specific Car Count

Stop counting the cars in the showroom when the count reaches 3:

PHP




The continue Statement

The continue keyword skips the current iteration and moves on to the next.

Example: Skipping Specific Motorcycles

Skip displaying a motorcycle’s brand if it’s the third one:

PHP




Alternative Syntax

PHP provides an alternative syntax for the while loop using endwhile. This can make your code more readable in some cases.

Example: Counting Cars

PHP




Increment by Steps

You can adjust the increment step to control how the loop progresses.

Example: Counting Cars by Tens

Let’s count cars in a parking lot, increasing the count by 10 each time, until we reach 100:

PHP
Tutorials dojo strip