The while Construct

The while construct creates a loop that executes as long as the condition evaluates to true. The condition is checked before each iteration. If the condition is false from the very beginning, the loop will not execute even once.

Syntax

phpwhile (condition) {
  // code to be executed
}

Example

Let's output numbers from 1 to 5:

php<?php
  $i = 1;
  while ($i <= 5) {
    echo $i;
    $i++;
  }
?>

Code execution result:

php12345

Example

Processing array elements:

php<?php
  $arr = [1, 2, 3, 4, 5];
  $i = 0;
  while ($i < count($arr)) {
    echo $arr[$i] * 2;
    $i++;
  }
?>

Code execution result:

php246810

Example

Infinite loop:

php<?php
  while (true) {
    // infinite loop
  }
?>

This code will run indefinitely until it is forcibly stopped.

See Also

  • the do-while construct,
    which checks the condition after loop execution
  • the for construct,
    which creates a loop with initialization, condition, and increment
  • the foreach construct,
    which iterates over array elements