PHP provides several types of looping statements that allow you to execute a block of code multiple times. These looping statements are:
while
loops: These loops execute a block of code as long as a condition istrue
. The condition is checked at the beginning of each iteration, so the code inside the loop may not be executed at all if the condition isfalse
to begin with.do...while
loops: These loops are similar towhile
loops, but the condition is checked at the end of each iteration instead of at the beginning. This means that the code inside the loop will be executed at least once, even if the condition isfalse
to begin with.for
loops: These loops are used to execute a block of code a predetermined number of times. They consist of three parts: an initialization expression, a condition, and an increment expression. The initialization expression is executed once at the beginning of the loop, the condition is checked at the beginning of each iteration, and the increment expression is executed at the end of each iteration.foreach
loops: These loops are used to iterate over arrays. They allow you to access each element of the array in turn and execute a block of code for each element.
Here is an example of each type of loop in PHP:
// while loop
$i = 1;
while ($i <= 10) {
echo $i . "\n";
$i++;
}
// do...while loop
$i = 1;
do {
echo $i . "\n";
$i++;
} while ($i <= 10);
// for loop
for ($i = 1; $i <= 10; $i++) {
echo $i . "\n";
}
// foreach loop
$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
echo $value . "\n";
}
In all of these examples, the loop will output the numbers 1 through 10, each on a new line.
You can also use the break
statement to exit a loop early, or the continue
statement to skip the rest of the current iteration and move on to the next one.
The break
statement can be used to exit any type of loop, while the continue
statement can be used to skip the rest of the current iteration in any type of loop except foreach
loops.
Here is an example of using the break
and continue
statements in a for
loop:
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . "\n";
}
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo $i . "\n";
}
The first loop will output the numbers 1 through 4, then exit the loop when $i
becomes 5. The second loop will output the odd numbers from 1 to 10 by skipping the rest of the current iteration whenever $i
is an even number.
It is important to use looping statements carefully, as it is easy to create infinite loops if the condition is always true
or if you forget to increment the loop variable.