Loops in PHP (for, while, foreach): A Complete Beginner’s Guide
php foreach loop
Loops are essential in PHP programming because they allow you to execute a block of code repeatedly. Whether you're processing arrays, generating dynamic content, or performing calculations, loops save time and make your code efficient.
This guide covers the three most commonly used loops in PHP:
for loop
while loop
foreach loop
Each loop is explained with syntax, examples, use cases, and best practices.
A loop allows you to run the same piece of code multiple times until a condition is met.
You use loops when:
You need repetition
You want to iterate through lists or arrays
You want to reduce code duplication
The for loop is used when you know exactly how many times you want to run the code.
for (initialization; condition; increment) {
// Code to execute
}
initialization → starting point
condition → loop runs while this is true
increment → updates the counter after each iteration
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>
<?php
for ($i = 2; $i <= 10; $i += 2) {
echo $i . " ";
}
?>
Use the while loop when you do NOT know the number of iterations in advance. The loop continues as long as the condition is true.
while (condition) {
// Code to execute
}
<?php
$count = 1;
while ($count <= 5) {
echo "Count: $count <br>";
$count++;
}
?>
<?php
$balance = 100;
while ($balance > 0) {
echo "Balance: $balance <br>";
$balance -= 20;
}
?>
The foreach loop is specifically designed for arrays. It loops through each item in the array without needing a counter.
foreach ($array as $value) {
// Code using $value
}
Or with keys:
foreach ($array as $key => $value) {
// Code using $key and $value
}
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
<?php
$ages = [
"Shubham" => 25,
"Amit" => 30,
"Ritu" => 28
];
foreach ($ages as $name => $age) {
echo "$name is $age years old.<br>";
}
?>
| Loop | Best Used When | Example Use Case |
|---|---|---|
| for | You know the number of iterations | Print 1 to 100 |
| while | Iterations depend on condition | Reduce balance until 0 |
| foreach | Iterating through arrays | Display users or items |
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) break;
echo $i;
}
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo $i;
}
Loops are the foundation of automation in PHP. Understanding for, while, and foreach loops will help you build efficient applications, process arrays, and handle repeated tasks with ease.
Practice each loop with different examples to fully master control flow in PHP.