What are the different types of loops in PHP?
In PHP, there are several types of loops you can use to execute a block of code repeatedly:
-
for Loop: Executes a block of code a specific number of times.
for ($i = 0; $i < 10; $i++) {
echo $i;
}
-
while Loop: Executes a block of code as long as the specified condition is true.
$i = 0;
while ($i < 10) {
echo $i;
$i++;
}
-
do...while Loop: Similar to the while loop, but guarantees that the block of code will be executed at least once before the condition is tested.
$i = 0;
do {
echo $i;
$i++;
} while ($i < 10);
-
foreach Loop: Iterates over arrays or objects, making it useful for working with collections of data.
$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
echo $value;
}
Each loop type has its own use case depending on the situation, such as the number of iterations or the type of data structure you're working with.