PHP loop is a programming structure that allows you to repeatedly execute a block of code as long as a certain condition is true.
There are several types of loops in PHP.
- While loop
- Do-while loop
- For loop
- Foreach loop
1. While loop:
The while loop is used when you want to execute the code as long as a condition is true.
<?php
$i = 0;
while ($i < 5) {
echo "Value Of i : $i <br>";
$i++;
}
?>
- Initialization Expression ($i = 0): You initialize the variable before the loop.
- Test Expression ($i < 5): The loop continues as long as this condition is true.
- Update Expression ($i++): You update the variable inside the loop.
Output:
Value Of i : 0
Value Of i : 1
Value Of i : 2
Value Of i : 3
Value Of i : 4
2. Do-while loop:
loops through a block of code once, and then repeats the loop as long as the specified condition is true
<?php
$i = 0;
do {
echo "Value of i : $i <br>";
$i++;
} while ($i < 5);
?>
Output:
Value Of i : 0
Value Of i : 1
Value Of i : 2
Value Of i : 3
Value Of i : 4
The block of code is executed once, and then the condition is checked.
3. For loop:
The for loop is used when you know the number of iterations beforehand.
<?php
for ($i = 0; $i < 5; $i++) {
echo "Value of i : $i <br>";
}
?>
- Initialization ($i = 0): The loop starts by initializing a variable ($i in this case).
- Condition ($i < 5): The loop continues as long as this condition is true.
- Update ($i++): After each iteration, the variable is updated. $i++ is a shorthand for $i = $i + 1.
Output:
Value Of i : 0
Value Of i : 1
Value Of i : 2
Value Of i : 3
Value Of i : 4
4. Foreach Loop:
Used for iterating over arrays or other iterable objects.
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "Color: $color <br>";
}
?>
Output:
Color: red
Color: green
Color: blue