PHP Loops
Repeating code execution efficiently
🔁 What are Loops?
Loops execute a block of code repeatedly as long as a specified condition is true. They help automate repetitive tasks and iterate through data structures like arrays efficiently.
<?php
for ($i = 1; $i <= 3; $i++) {
echo "Count: $i <br>";
}
?>
Output:
Count: 1
Count: 2
Count: 3
Types of Loops
for Loop
Executes code a specific number of times with a counter variable, ideal when iteration count is known beforehand.
<?php
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>
while Loop
Repeats code while a condition remains true, checking the condition before each iteration begins.
<?php
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}
?>
do...while Loop
Executes code at least once, then repeats while condition is true, checking condition after each iteration.
<?php
$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);
?>
foreach Loop
Iterates through arrays and objects, accessing each element without manual index management, simplifying array traversal.
<?php
$arr = [1, 2, 3];
foreach ($arr as $val) {
echo $val;
}
?>
🔹 for Loop
Use when you know how many times to loop:
<?php
// Basic for loop
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
echo "<br>";
// Counting backwards
for ($i = 5; $i >= 1; $i--) {
echo "$i... ";
}
echo "Blast off!<br><br>";
// Increment by 2
for ($i = 0; $i <= 10; $i += 2) {
echo "$i ";
}
echo "<br><br>";
// Multiplication table
for ($i = 1; $i <= 5; $i++) {
echo "5 x $i = " . (5 * $i) . "<br>";
}
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
5... 4... 3... 2... 1... Blast off!
0 2 4 6 8 10
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
🔹 while Loop
Loop while a condition is true:
<?php
// Basic while loop
$count = 1;
while ($count <= 5) {
echo "Count: $count<br>";
$count++;
}
echo "<br>";
// Sum numbers
$sum = 0;
$num = 1;
while ($num <= 10) {
$sum += $num;
$num++;
}
echo "Sum of 1 to 10: $sum<br><br>";
// User input simulation
$password = "secret";
$attempt = "wrong";
$tries = 0;
while ($attempt != $password && $tries < 3) {
$tries++;
echo "Attempt $tries: Incorrect password<br>";
// In real scenario, get user input here
if ($tries == 2) $attempt = "secret"; // Simulate correct on 3rd try
}
if ($attempt == $password) {
echo "Access granted!";
}
?>
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Sum of 1 to 10: 55
Attempt 1: Incorrect password
Attempt 2: Incorrect password
Access granted!
🔹 do...while Loop
Execute code at least once, then check condition:
<?php
// Basic do...while
$i = 1;
do {
echo "Number: $i<br>";
$i++;
} while ($i <= 5);
echo "<br>";
// Executes at least once even if condition is false
$x = 10;
do {
echo "This runs once even though x is not less than 5<br>";
$x++;
} while ($x < 5);
echo "<br>";
// Menu system example
$choice = 0;
$menuShown = 0;
do {
$menuShown++;
echo "Menu (shown $menuShown time)<br>";
echo "1. Option One<br>";
echo "2. Option Two<br>";
echo "3. Exit<br><br>";
// Simulate user choosing exit on 2nd show
if ($menuShown == 2) $choice = 3;
} while ($choice != 3);
echo "Goodbye!";
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
This runs once even though x is not less than 5
Menu (shown 1 time)
1. Option One
2. Option Two
3. Exit
Menu (shown 2 time)
1. Option One
2. Option Two
3. Exit
Goodbye!
🔹 foreach Loop
Loop through arrays easily:
<?php
// Simple array
$colors = ["Red", "Green", "Blue", "Yellow"];
foreach ($colors as $color) {
echo "$color<br>";
}
echo "<br>";
// Array with index
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit<br>";
}
echo "<br>";
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
echo "<br>";
// Array of arrays
$students = [
["name" => "Alice", "grade" => "A"],
["name" => "Bob", "grade" => "B"],
["name" => "Charlie", "grade" => "A"]
];
foreach ($students as $student) {
echo $student["name"] . " got grade " . $student["grade"] . "<br>";
}
?>
Output:
Red
Green
Blue
Yellow
0: Apple
1: Banana
2: Orange
name: John
age: 30
city: New York
Alice got grade A
Bob got grade B
Charlie got grade A
🔹 break and continue
Control loop execution flow:
<?php
// break - exit loop completely
echo "Using break:<br>";
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
echo "Breaking at $i<br>";
break;
}
echo "$i ";
}
echo "<br><br>";
// continue - skip current iteration
echo "Using continue:<br>";
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "$i "; // Only odd numbers printed
}
echo "<br><br>";
// Practical example
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
echo "Find first number greater than 5:<br>";
foreach ($numbers as $num) {
if ($num <= 5) {
continue;
}
echo "Found: $num";
break;
}
?>
Output:
Using break:
1 2 3 4 Breaking at 5
Using continue:
1 3 5 7 9
Find first number greater than 5:
Found: 6
🔹 Nested Loops
Loops inside other loops:
<?php
// Multiplication table
echo "Multiplication Table:<br>";
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
$result = $i * $j;
echo "$i x $j = $result<br>";
}
echo "<br>";
}
// Pattern printing
echo "Pattern:<br>";
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br>";
}
?>
Output:
Multiplication Table:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
Pattern:
*
* *
* * *
* * * *