Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

while Loop

The PHP while Loop

The while loop runs a block of code as long as the specified condition is true.

Example

Display $i as long as $i is less than 6:

$i = 1;
while ($i < 6) {
  echo $i;
 $i++;
}
Note: Don’t forget to increment $i, or the loop will run indefinitely.

The while loop doesn’t run a set number of times but checks after each iteration if the condition is still true.

The condition doesn’t need to be a counter; it could be the status of an operation or any condition that evaluates to true or false.

The break Statement

We can use the break statement to stop the loop, even if the condition remains true:

Example$i

Terminate the loop when $i is 3:

$i = 1
while ($i < 6) {
 if ($i == 3) break;
 echo $i;
 $i++;
}

 

The continue Statement

The continue statement allows us to skip the current iteration and move on to the next one:

 

Example

Skip to the next iteration if $i is 3:

$i = 0
while ($i < 6) {
 $i++;
 if ($i == 3) continue;
 echo $i;
}

Alternative Syntax

The while loop syntax can also be expressed using the endwhile statement, as follows:

Example

Output $i as long as $i is less than 6:

$i = 1
while ($i < 6):
 echo $i;
 $i++;
endwhile;

Step 10

If you want the while loop to count to 100 in increments of 10, you can increase the counter by 10 instead of 1 in each iteration:

Example

Count to 100 in increments of ten:

$i = 0;
while ($i < 100) {
 $i+=10;
 echo $i "<br>";
}