Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The while loop in PHP is a pre-test control flow statement that repeatedly executes a block of code as long as a specified boolean condition evaluates to true. Because the condition is evaluated before each iteration, the loop body will execute zero times if the initial condition evaluates to false.

Syntax

PHP supports two syntactical structures for the while loop: the standard curly-brace syntax and the alternative colon-based syntax (commonly used in templating). Standard Syntax:
while (expression) {
    // Statements to execute
}
Alternative Syntax:
while (expression):
    // Statements to execute
endwhile;

Execution Mechanics

  1. Expression Evaluation: At the start of each iteration, PHP evaluates the expression.
  2. Type Casting: PHP automatically casts the result of the expression to a boolean. Values considered “truthy” (e.g., non-zero integers, non-empty strings, populated arrays) evaluate to true. Values considered “falsy” (e.g., 0, 0.0, "", null, [], false) evaluate to false.
  3. Execution: If the expression is true, the statements within the block are executed sequentially.
  4. Re-evaluation: Once the block completes, execution returns to step 1. This cycle continues until the expression evaluates to false.

State Mutation

To prevent an infinite loop, the code block within the while loop must eventually mutate the state of the variables evaluated in the expression.
$iteration = 0;

while ($iteration < 3) {
    echo $iteration;
    $iteration++; // Mutates state to eventually yield a false condition
}
// Output: 012

Loop Control Statements

PHP provides specific keywords to alter the standard execution flow of a while loop from within its block:
  • break: Immediately terminates the execution of the while loop. Program control resumes at the next statement following the loop block. You can pass an optional integer argument (e.g., break 2;) to break out of multiple nested loops.
  • continue: Halts the current iteration, skipping any remaining statements in the block, and immediately jumps back to the expression evaluation to begin the next iteration. Like break, it accepts an optional integer argument to skip iterations of nested loops.
$i = 0;

while ($i < 5) {
    $i++;
    
    if ($i === 2) {
        continue; // Skips the echo for $i = 2
    }
    
    if ($i === 4) {
        break; // Terminates the loop entirely
    }
    
    echo $i;
}
// Output: 13
Master PHP with Deep Grasping Methodology!Learn More