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.
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:
$motorcycleCount = 1; while ($motorcycleCount < 6) { echo $motorcycleCount; $motorcycleCount++; }
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:
$carCount = 1; while ($carCount < 6) { if ($carCount == 3) break; echo $carCount; $carCount++; }
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:
$motorcycleIndex = 0; while ($motorcycleIndex < 6) { $motorcycleIndex++; if ($motorcycleIndex == 3) continue; echo $motorcycleIndex; }
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
$carCount = 1; while ($carCount < 6): echo $carCount; $carCount++; endwhile;
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:
$carCount = 0; while ($carCount < 100) { $carCount += 10; echo $carCount . "<br>"; }