This tutorial will teach you how to use the while statement to build loops in the PHP programming language and show some examples.
The while loop is the most straightforward kind of loop in PHP. The code inside the loop will execute for as long as the while condition is true. Change the condition, and the loop will exit.
while loops are a fundamental part of PHP (and loops are an essential part of computer programming in general) – so it’s good to know how they work and what they can be used for.
Loops are commonly used for iterating through arrays of values, counting, and retrying actions until they succeed. Loops are also commonly used for processing queues.
What is a while Loop
A while loop will execute a block of code while a given condition is true. When that condition changes to false, the loop will exit, and the code following it will continue executing.
It is similar to a do while loop – but a do while loop checks the condition after the statements in the loop are executed.
PHP while Loop Syntax
The PHP while loop has the following syntax:
while (CONDITION){ STATEMENTS }
Note that:
- CONDITION can be any PHP expression
- STATEMENTS can be any number of lines of PHP code that will be executed every time the loop repeats
- The while loop will execute the STATEMENTS so long as the CONDITION expression evaluates as true or truthy.
- So, to break out of the while loop, your STATEMENTS will need to change something in the CONDITION so that it can no longer be considered true.
PHP while Loop Examples
Below are some example while loops. Notice that the statements inside each loop will at some point alter the condition used for the while loop so that the loop is exited:
$i = 1; while ($i <= 5){ echo $i; $i++; }
Above, a while loop is executed with the condition that the variable $i is less than or equal to 5. The code statements executed by the loop increment the value of $i after printing it – so that eventually, the condition which exits the loop is met.
It’s also possible to write a while loop without code brackets if you only want to execute a single statement:
$i = 1; while( $i <= 5 ) echo $i++;
Above, the loop will execute until $i reaches 5. The echo statement will print the value of $i before it is incremented by the ++ operator.
Watch Out for Infinite Loops!
If your loop never reaches a condition that will cause it to exit, your loop will run indefinitely, freezing your application! This is called an infinite loop and should be avoided at all costs!