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.
Example
<?php
$i = 0;

while ($i < 5) {
echo "The value of i is: $i<br>";
$i++;
}
?>
Try it yourself

Infinite Loop


Be careful with the while loop condition. If the condition never becomes false, you can end up with an infinite loop.

Example
<?php
$count = 1;
while ($count <= 3) {
echo "This will run forever if the count is not incremented.<br>";
// $count++; // Uncommenting this will prevent the infinite loop
}
?>
Try it yourself

Using while Loop with break


You can use the break statement to exit the loop when a specific condition is met.

Example
<?php
$i = 0;
while (true) {
echo "The value of i is: $i<br>";
$i++;
if ($i == 3) {
break; // Exit the loop when $i equals 3
}
}
?>
Try it yourself

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.

Example
<?php
$i = 0;
while ($i < 5) {
$i++;
if ($i == 3) {
continue; // Skip the rest of the code when $i equals 3
}
echo "The value of i is: $i<br>";
}
?>
Try it yourself

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;
Example
<?php
$i = 0;
while ($i < 5):
echo "The value of i is: $i<br>";
$i++;
endwhile;
?>
Try it yourself