In PHP, there are several types of loops available to iterate over arrays, perform repetitive tasks, and control the flow of execution. Here are the main types of loops in PHP:
for
loop:
Thefor
loop is used when you know the number of iterations in advance.
for ($i = 0; $i < 5; $i++) {
// Code to be executed
}
PHPwhile
loop:
Thewhile
loop is used when you want to repeat a block of code as long as a condition is true.
$i = 0;
while ($i < 5) {
// Code to be executed
$i++;
}
PHPdo-while
loop:
Thedo-while
loop is similar to thewhile
loop, but it always executes the code block at least once, regardless of the condition.
$i = 0;
do {
// Code to be executed
$i++;
} while ($i < 5);
PHPforeach
loop:
Theforeach
loop is specifically designed for iterating over arrays or objects.
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
// Code to be executed for each element
echo $fruit;
}
PHPbreak
andcontinue
statements:
Thebreak
statement is used to exit a loop prematurely, while thecontinue
statement is used to skip the current iteration and move to the next one.
for ($i = 0; $i < 5; $i++) {
if ($i == 2) {
break; // Exit the loop when $i equals 2
}
if ($i == 1) {
continue; // Skip the current iteration when $i equals 1
}
// Code to be executed
}
PHP
These are the most commonly used loop structures in PHP. They allow you to efficiently perform repetitive tasks and control the flow of execution based on certain conditions.