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
<!DOCTYPE html>
<html>
<body>

<?php
$i = 0;

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

</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?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
}
?>
</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?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
}
}
?>
</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?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>";
}
?>

</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;

while ($i < 5):
echo "The value of i is: $i<br>";
$i++;
endwhile;
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.