loops Overview
Overview of PHP Loops
Loops in PHP are used to execute a block of code repeatedly as long as a specified condition is true. They are essential for tasks that require repetition, such as iterating over arrays, generating sequences, or processing data.
1. while Loop
The while loop executes a block of code as long as the condition is true.
while (condition) {
// Code to be executed
}
Example:
<?php
$i = 1;
while ($i <= 5) {
echo $i . "<br>";
$i++;
}
?>
Output
2
3
4
5
2. do...while Loop
This loop is similar to while, but it ensures that the code block runs at least once, even if the condition is false at the start.
do {
// Code to be executed
} while (condition);
Example:
<?php
$i = 1;
do {
echo $i . "<br>";
$i++;
} while ($i <= 5);
?>
Output
2
3
4
5
3. for Loop
The for loop is used when the number of iterations is known. It has three parts: initialization, condition, and increment/decrement.
for (initialization; condition; increment) {
// Code to be executed
}
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>
Output
2
3
4
5
4. foreach Loop
The foreach loop is specifically used to iterate over arrays.
foreach ($array as $value) {
// Code to be executed
}
With key-value pairs:
foreach ($array as $key => $value) {
// Code using $key and $value
}
Example:
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
Output
green
blue
Associative Array Example:
<?php
$user = ["name" => "John", "age" => 25];
foreach ($user as $key => $value) {
echo "$key: $value<br>";
}
?>
Output
age: 25
5. Loop Control Statements
break: Exits the loop immediately.
continue: Skips the current iteration and continues with the next one.
Example with break:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) break;
echo $i . "<br>";
}
?>
Output
2
3
4
5
Example with continue:
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo $i . "<br>";
}
?>
Output
2
4
5
Summary Table
Loop Type | Best Use Case |
---|---|
while | When condition is checked before loop |
do...while | When code must run at least once |
for | When number of iterations is known |
foreach | When working with arrays |
break | To exit a loop early |
continue | To skip current loop iteration |
Conclusion
PHP loops are powerful tools for repeating code efficiently. Choosing the right loop depends on your specific use case—whether you're iterating through a numeric range, an array, or performing a task until a condition is met.
Understanding these loop structures is fundamental to writing efficient PHP applications that can handle repetitive tasks with ease.