PHP do while Loop

0
4كيلو بايت

The do...while loop - Loops through a block of code once, and then repeats the loop as long as the specified condition is true.


The PHP do...while Loop

The do...while loop will always execute the block of code at least once, it will then check the condition, and repeat the loop while the specified condition is true.

ExampleGet your own PHP Server

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

$i = 1;

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

Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means that the do...while loop will execute its statements at least once, even if the condition is false. See example below.

Let us see what happens if we set the $i variable to 8 instead of 1, before execute the same do...while loop again:

Example

Set $i = 8, then print $i as long as $i is less than 6:

$i = 8;

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

The code will be executed once, even if the condition is never true.



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;

do {
  if ($i == 3) break;
  echo $i;
  $i++;
} while ($i < 6);
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;

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

البحث
الأقسام
إقرأ المزيد
أخرى
PHP Nested if Statement
Nested If You can have if statements inside if statements, this is...
بواسطة PHP Tutorial 2024-05-17 07:47:26 0 4كيلو بايت
أخرى
PHP Introduction
PHP code is executed on the server. What You Should Already Know Before you continue you...
بواسطة PHP Tutorial 2024-05-17 07:08:40 0 4كيلو بايت
أخرى
PHP Array Functions
PHP Array Functions PHP has a set of built-in functions that you can use on arrays....
بواسطة PHP Tutorial 2024-05-17 08:07:42 1 8كيلو بايت
أخرى
PHP Arrays
An array stores multiple values in one single variable: ExampleGet your own PHP Server $cars...
بواسطة PHP Tutorial 2024-05-17 07:53:31 0 6كيلو بايت
أخرى
تطورات التعلم الآلي وتأثيرها على مستقبل العمل
مقدمة: في ظل التطورات السريعة للتكنولوجيا والابتكار، أصبح التعلم الآلي...
بواسطة MOHAMED ATTALLAH 2024-05-14 13:56:58 0 7كيلو بايت
Sociallez https://sociallez.com