PHP while Loop

0
5K

The while loop - Loops through a block of code as long as the specified condition is true.


The PHP while Loop

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

ExampleGet your own PHP Server

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

$i = 1;
while ($i < 6) {
  echo $i;
  $i++;
}
Try it Yourself »

Note: remember to increment $i, or else the loop will continue forever.

The while loop does not run a specific number of times, but checks after each iteration if the condition is still true.

The condition does not have to be a counter, it could be the status of an operation or any condition that evaluates to either true or false.


The break Statement

With the break statement we can stop the loop even if the condition is still true:

Example

Stop the loop when $i is 3:

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


The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Stop, and jump to the next iteration if $i is 3:

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

Alternative Syntax

The while loop syntax can also be written with the endwhile statement like this

Example

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

$i = 1;
while ($i < 6):
  echo $i;
  $i++;
endwhile;
Try it Yourself »

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:

Example

Count to 100 by tens:

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

PHP Exercises

Test Yourself With Exercises

Exercise:

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

$i = 1; 

 ($i < 6) 
  echo $i;
  $i++;


Start the Exercise

Pesquisar
Categorias
Leia Mais
Outro
PHP Create Arrays
Create Array You can create arrays by using the array() function: ExampleGet your...
Por PHP Tutorial 2024-05-17 08:01:55 0 8K
Outro
PHP Update Array Items
Update Array Item To update an existing array item, you can refer to the index number for...
Por PHP Tutorial 2024-05-17 08:02:49 0 7K
Outro
PHP Array Functions
PHP Array Functions PHP has a set of built-in functions that you can use on arrays....
Por PHP Tutorial 2024-05-17 08:07:42 1 8K
Outro
PHP - Concatenate Strings
String Concatenation To concatenate, or combine, two strings you can use...
Por PHP Tutorial 2024-05-17 07:30:24 0 9K
Outro
PHP - Escape Characters
Escape Character To insert characters that are illegal in a string, use an escape character. An...
Por PHP Tutorial 2024-05-17 07:32:36 0 11K
Sociallez https://sociallez.com