PHP while loops

Table of Contents

PHP while loops

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++; } ?>

Example 1

Result View Example

PHP break statement

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++; }

?>

Example 2

Result View Example

PHP continue_Statement

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; } ?>

Example 3

Result View Example

PHP Alternative Syntax

<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; ?>

Example 4

Result View Example

PHP Step 10

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>"; }

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference