In PHP, loops are used to execute a block of code repeatedly as long as a specified condition is true. They provide a way to iterate over arrays, manipulate data, and perform repetitive tasks efficiently. Here’s an overview of PHP loops along with examples:
In PHP, loops are used to execute a block of code repeatedly as long as a specified condition is true. They provide a way to iterate over arrays, manipulate data, and perform repetitive tasks efficiently. Here’s an overview of PHP loops along with examples:
The while loop executes a block of code as long as the specified condition is true.
while (condition) { // code to be executed }
$i = 1; while ($i <= 5) { echo "The number is: $i <br>"; $i++; }
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition.
do { // code to be executed } while (condition);
$i = 1;
do {
echo "The number is: $i <br>";
$i++;
} while ($i <= 5);
The for loop is used when you know in advance how many times the code should be executed.
for (initialization; condition; increment/decrement) { // code to be executed }
for ($i = 1; $i <= 5; $i++) {
echo "The number is: $i <br>";
}
The foreach loop is used to iterate over arrays.
foreach ($array as $value) { // code to be executed }
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo "The color is: $color <br>";
}
PHP also provides loop control statements to alter the flow of loops.
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Terminate the loop if $i equals 5
}
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . "<br>";
}
PHP loops provide a powerful way to iterate over data and perform repetitive tasks efficiently. They are essential for building dynamic and responsive applications, especially when working with arrays or processing large sets of data.