Table of Contents
The while loop executes a block of code as long as the specified condition is true.
<h4>PHP while-Loops </h4>
<p></p>
<?php
// while loop
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Result View Example
With the break statement we can stop the loop even if the condition is still true:
<h4>PHP while-Loops break Statement</h4>
<p>With the break statement we can stop the loop even if the condition is still true:</p>
<?php
// while loop break Statement
$i = 1;
while ($i <= 6) {
if ($i == 3) {
break;
}
echo "The number is: $i <br>";
$i++;
}
?>
Result View Example
With the continue statement we can stop the current iteration, and continue with the next:
<h4>PHP while-Loops continue_Statement</h4>
<p>Stop, and jump to the next iteration if $i is 3:</p>
<?php
// while loop continue_Statement
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
?>
Result View Example
<h4>PHP while-Loops Alternative Syntax</h4>
<p>The while loop syntax can also be written with the endwhile statement like this</p>
<?php
// while loop Alternative Syntax
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
?>
Result View Example
If you want the while loop count to 100, but only by each 10, you can increase the counter by 10 instead 1 in each iteration:
// while loop step 10
$i = 0;
while ($i < 100) {
$i+=10;
echo "$i<br>";
}
Result View Example
Document in project
You can Download PDF file.