Loops are used to execute the same block of code repeatedly as long as a certain condition is true. The while loop is the simplest type of loop in PHP, checking its condition before each iteration.
As long as the condition evaluates to true, the code within the braces will keep running.
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++; // This is CRITICAL!
}
?>
A functional while loop usually has three main parts:
$x = 1; — Sets the starting point.$x <= 5 — The loop runs only if this is TRUE.$x++; — Updates the counter so the condition eventually becomes FALSE.$x++), the condition will always be true, and your browser/server might crash!
You can change the update logic to skip numbers or calculate differently.
<?php
$x = 0;
while($x <= 100) {
echo "Percentage: $x% <br>";
$x += 10;
}
?>
while loop will never execute.
while loops when you don't know exactly how many times the code needs to run (e.g., reading rows from a database until no rows are left).