PHP Loops
PHP provides several types of loops that allow you to repeat a block of code multiple times. The most commonly used loops in PHP are:
- for loop: The for loop executes a block of code a fixed number of times.
php
for ($i = 0; $i < 5; $i++) {
// Code to be executed
echo "The value of i is: " . $i . "<br>";
}
This loop will iterate five times, starting from $i = 0
and incrementing $i
by 1 in each iteration.
- while loop: The while loop executes a block of code as long as a specified condition is true.
php
$i = 0;
while ($i < 5) {
// Code to be executed
echo "The value of i is: " . $i . "<br>";
$i++;
}
This loop will keep executing as long as $i
is less than 5. It increments $i
by 1 in each iteration.
- do-while loop: The do-while loop is similar to the while loop, but it executes the code block at least once, even if the condition is initially false.
php
$i = 0;
do {
// Code to be executed
echo "The value of i is: " . $i . "<br>";
$i++;
} while ($i < 5);
This loop will execute the code block at least once, and then it will continue executing as long as $i
is less than 5.
- foreach loop: The foreach loop is used to iterate over elements in an array or objects in an iterable object.
php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
// Code to be executed
echo "The color is: " . $color . "<br>";
}
This loop iterates over each element in the $colors
array and assigns the current element to the variable $color
.
These are the basic loop structures available in PHP. Each loop has its own use case, and you can choose the one that best fits your needs based on the specific requirements of your program.