PHP Loops
PHP Loops are used to execute the same block of code again and again, as long as a certain condition is true.
Following loop types in PHP:
- PHP while - loops through a block of code as depend data length as the specified condition is true
- PHP do...while - loops through a block of code once, and then repeats the loop as depend data length as the specified condition is true
- PHP for - loop through a block of code a specified number of time or count of data or length
- PHP foreach - loops through a block of code for each index in an array
The PHP while - loops
The while loop executes a block of code as depend data length as the specified condition is true
Syntax
while (condition is true) {
code to be executed;
}
Example for while loop:
The example below displays the numbers from 1 to 3 :
<?php
$a = 1;
while($a <= 3) {
echo "This Number is: $a <br>";
$a++;
}
?>
Explained above Example :
$a = 1; - Initialise the while loop counter ($a), and set the start value to 1
$a <= 3 - Continue the loop as long as $a is less than or equal to 3
$a++; - We will Increase the loop counter value by 1 for each iteration
PHP do…while Loop
The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.
Syntax
do{
// Code to be executed
}
while(condition);
Example for while loop:
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 6);
?>
Explained above Example :
The following example define a loop that starts with $i=1. It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 6.