PHP While Loops
- Previous Page PHP Switch
- Next Page PHP For Loop
The PHP while loop executes the code block when the specified condition is true.
PHP Loops
When you are writing code, you often need to repeatedly run the same code block. We can use loops to perform such tasks instead of adding several almost identical code lines in the script.
In PHP, we have the following loop statements:
- while - Repeat the code block as long as the specified condition is true
- do...while - Execute the code block first, then repeat the loop as long as the specified condition is true
- for - Loop the code block a specified number of times
- foreach - Traverse each element in the array and loop the code block
PHP While Loops
The while loop will execute the code block as long as the specified condition is true.
Syntax
while (condition is true) { Code to be executed; }
The following example first sets the variable $x to 1 ($x=1). Then, the while loop is executed as long as $x is less than or equal to 5. Each time the loop runs, $x is incremented by 1:
Example
<?php $x=1; while($x<=5) { echo "This number is: $x <br>"; $x++; } ?>
PHP do...while Loop
The do...while loop first executes the code block, then checks the condition, and if the specified condition is true, it repeats the loop.
Syntax
do { Code to be executed; } while (condition is true);
The following example first sets the variable $x to 1 ($x=1). Then, the do while loop outputs a string, then increments the variable $x by 1. Subsequently, the condition is checked ($x is less than or equal to 5). As long as $x is less than or equal to 5, the loop will continue to run:
Example
<?php $x=1; do { echo "This number is: $x <br>"; $x++; } while ($x<=5); ?>
Please note that the do while loop checks the condition only after executing the statements inside the loop. This means that the do while loop will execute at least one statement, even if the condition test fails on the first try.
The following example sets $x to 6, then runs the loop,Check the condition afterwards:
Example
<?php $x=6; do { echo "This number is: $x <br>"; $x++; } while ($x<=5); ?>
The next section will explain the for loop and foreach loop.
- Previous Page PHP Switch
- Next Page PHP For Loop