PHP While Loop

Updated: April 20th, 2022, 05:27:49 IST
Published: April 20th, 2022
PHP While Loop
Title: PHP While Loop

While loops are the most basic sort of PHP loop. They act just like their C counterparts. The while loop executes through a block of code as long as the specified condition is true.

While Loop

The meaning of a while statement is simple. It prompts PHP to run the nested statement(s) as many times as the while expression evaluates to true.

Because the value of the expression is checked each time the loop begins, even if it changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration).

If the while expression evaluates to false from the start, the nested statement(s) will never be executed.

Syntax

while (condition is true) {
  code to be executed;
}

Examples

The example below shows the numbers from 1 to 10:

Example #1

<?php
$n = 1;

while($n <= 10) {
  echo "The number is: $n <br>";
  $n++;
}
?>

Example Explained

  • $n = 1; - Initialize the variable ($n), and set the value to 1
  • $n <= 5 - Continue the loop as long as $n is less than or equal to 10
  • $n++; - Increase the loop variable $n value by 1 for each iteration

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1st */

$n = 1;
while ($n <= 10) {
    echo $n++;  /* the printed value would be
                   $n before the increment
                   (post-increment) */
}

/* example 2nd */

$n = 1;
while ($n <= 10):
    echo $n;
    $n++;
endwhile;
?>