Published by: Sujan
Published date: 16 Jun 2021
Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort. PHP supports four different types of loops.
The while statement will loops through a block of code as long as the condition specified in the while statement evaluates to true.
while(condition){
// Code to be executed
}
The do-while loop is a variant of the 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.
do{ // Code to be executed
}
while(condition);
The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code a certain number of times.
for(initialization; condition; increment){
// Code to be executed
}
The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}
There is one more syntax foreach loop, which is extension of the first.
foreach($array as $key => $value){
//Code to be executed
}