Loops (for, while, foreach)
Loops in PHP are used to execute a block of code repeatedly until a specified condition is met. They are essential for tasks like iterating through arrays, processing data, and automating repetitive actions.
For
Loop
The for loop executes a block of code a specific number of times.
It is commonly used when you know in advance how many times the loop should
run.
Example:
<?php
for
($i = 1; $i <= 5; $i++) {
echo "Number: $i\n";
}
?>
Output:
Number:
1
Number:
2
Number:
3
Number:
4
Number:
5
While
Loop
The while loop executes a block of code as long as a specified
condition is true. It is useful when the number of iterations is not known
beforehand.
Example:
<?php
$i
= 1;
while
($i <= 5) {
echo "Number: $i\n";
$i++;
}
?>
Output:
Number:
1
Number:
2
Number:
3
Number:
4
Number:
5
Do-While
Loop
The do-while loop is similar to while, but it guarantees that the code block is executed at least
once, even if the condition is false.
Example:
<?php
$i
= 6;
do
{
echo "Number: $i\n";
$i++;
}
while ($i <= 5);
?>
Output:
Number:
6
Foreach
Loop
The foreach loop is specifically used to iterate over arrays. It
provides an easy way to access each element without using a counter.
Example:
<?php
$colors
= ["Red", "Green", "Blue"];
foreach
($colors as $color) {
echo "Color: $color\n";
}
?>
Output:
Color:
Red
Color:
Green
Color:
Blue
Conclusion
Loops in PHP allow you to automate
repetitive tasks efficiently. Using for, while,
do-while, and foreach loops, you can handle arrays, counters, and dynamic
conditions to build flexible and scalable web applications.