Advertisement
Google Ad Slot: content-top
PHP while Loop
The while loop in PHP is a control structure that allows you to repeatedly execute a block of code as long as a specified condition evaluates to true.
Syntax
while (condition) {
// Code to be executed as long as the condition is true
}
condition: The loop will continue to execute the code block as long as this condition is true. The condition is checked at the beginning of each iteration.
Infinite Loop
Be careful with the while loop condition. If the condition never becomes false, you can end up with an infinite loop.
Using while Loop with break
You can use the break statement to exit the loop when a specific condition is met.
Using while Loop with continue
The continue statement can be used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
Alternative Syntax
PHP offers an alternate syntax for control structures like while loops, which can make code more readable when embedded in HTML templates. The alternate syntax is particularly useful when mixing PHP and HTML, as it avoids the need for curly braces {} by using : and endwhile;.
Syntax of the Alternate while Loop
while (condition): // Code to execute as long as condition is true endwhile;