A loop is a programming construct that allows you to repeat a set of instructions or a block of code multiple times. It's a way to automate repetitive tasks without having to write the same code over and over again until the condition is false.
PHP supports following four loop types:
It allows you to repeat a block of code for a specific number of times or for each item in a collection.
<?php
for (initialization; condition; increment/decrement)
{
// code to be executed
}
?>
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>
The while loop executes a block of code until the specified condition is true.
It is used if the number of iterations is unknown.
<?php
while ($condition) {
// code to be executed
}
?>
<?php
$count = 10;
while ($count > 0) {
echo $count . "<br>";
$count--;
}
?>
The do-while statement is executed atleast once, then will repeat the loop as long as a condition is true.
<?php
do
{
// code to be executed
} while (condition);
?>
<?php
$count = 1;
do
{
echo $count . "<br>";
$count++;
} while ($count <= 5);
?>
The foreach loop in PHP is used to iterate over arrays or other iterable objects. Its syntax is straightforward and simplifies the process of iteration through through the elements of an array.
<?php
foreach ($array as $element)
{
// code to be executed for each $element in $array
}
?>
<?php
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $value)
{
echo $value . "<br>";
}
?>
Continue - The continue statement is particularly useful when you want to skip certain iterations based on a condition, allowing you to control the flow of your loop more precisely.
<?php
while ($condition) {
// code before continue
if ($condition_to_skip) {
continue; // skip the rest of the loop for the current iteration
}
// code after continue
}
?>
The break statement is used to jump out of a loop prematurely. It is typically used within a loop (such as for, while, or do-while) to immediately terminate the loop's execution.
<?php
while ($condition) {
// code before break
if ($condition_to_exit) {
break; // exit the loop
}
// code after break
}
?>
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
// Exit the loop when $i is 3
break;
}
echo $i . "<br>"; // 1 2
}
?>