Loops
Loops
Loops are used to run a block of code again and again as long as a condition remains true, which helps reduce repetition of code.
Types of Loops
- while loop
- do...while loop
- for loop
- foreach loop
while loop
The while loop is used to execute a block of code repeatedly as long as a condition is true. It checks the condition before each iteration.
Syntax
while (condition) {
// code to be executed
}
Example
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
?>
do while Loop
The do...while loop is used to execute a block of code at least once, and then it repeats the execution as long as the condition is true.
Syntax
do {
// code to be executed
} while (condition);
Example
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 5);
?>
for Loop
The for loop is used to execute a block of code a fixed number of times. It is mainly used when the number of iterations is known in advance.
Syntax
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
?>
foreach Loop
The foreach loop is used to iterate over arrays. It goes through each element of an array one by one.
Syntax
foreach ($array as $value) {
// code to be executed
}
Example
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . " ";
}
?>