What is a Loop?
A loop is a way to repeat the same block of code multiple times. Instead of writing the same code over and over, you write it once and put it inside a loop that runs until a certain condition is met. This is essential for tasks like processing items in an array, reading database records, or generating repetitive HTML content.
The 4 Main Types of Loops in PHP
PHP has four primary types of loops, each with slightly different use cases:
while
do...while
for
foreach
1. The while
Loop
The while
loop executes a block of code as long as a specified condition is true
.
- Key Point: It checks the condition before the code block is executed. If the condition is
false
from the start, the code block won't run at all.
Syntax:
while (condition is true) {
// code to be executed
}
Example:
$count = 1;
while ($count <= 5) {
echo "The number is: $count <br>";
$count++; // Increment the counter
}
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Use Case: Use a while
loop when you don't know in advance how many times you need to loop. For example, reading lines from a file until you reach the end.
2. The do...while
Loop
The do...while
loop will always execute the block of code once, and then it will check the condition. If the condition is true
, it will repeat the loop.
- Key Point: It checks the condition after the code block is executed. This guarantees the code runs at least one time.
Syntax:
do {
// code to be executed
} while (condition is true);
Example:
$number = 10;
do {
echo "The number is: $number <br>";
$number++;
} while ($number <= 5); // Condition is false from the start!
Output:
The number is: 10
Even though the condition ($number <= 5)
is false
on the first check, the code block ran once.
Use Case: Useful for tasks that must run at least once, like checking user input from a form and then asking for input again if it's invalid.
3. The for
Loop
The for
loop is used when you know exactly how many times you want to execute a block of code. It combines the counter initialization, condition, and increment into one line.
Syntax:
for (init counter; test counter; increment counter) {
// code to be executed
}
init counter
: Initialize the loop counter value (e.g.,$i = 1;
).test counter
: Evaluated for each loop iteration. If it evaluates totrue
, the loop continues.increment counter
: Increases the loop counter value (e.g.,$i++
).
Example:
for ($i = 0; $i < 5; $i++) {
echo "The value of i is: $i <br>";
}
Output:
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
Use Case: Perfect for iterating a specific number of times, like looping through a known range of numbers or repeating an HTML element a set number of times.
4. The foreach
Loop
The foreach
loop is specifically designed for iterating over arrays and objects. It's the simplest and easiest way to loop through each key/value pair in an array.
Syntax (for indexed arrays):
foreach ($array as $value) {
// code to be executed
}
Syntax (for associative arrays):
foreach ($array as $key => $value) {
// code to be executed
}
Example:
$fruits = array("Apple", "Banana", "Orange", "Mango");
// Loop through values
foreach ($fruits as $fruit) {
echo "I love $fruit! <br>";
}
// Loop through keys and values
$user = array("name" => "John", "age" => 30, "city" => "Paris");
foreach ($user as $key => $value) {
echo "Key: $key; Value: $value <br>";
}
Output:
I love Apple!
I love Banana!
I love Orange!
I love Mango!
Key: name; Value: John
Key: age; Value: 30
Key: city; Value: Paris
Use Case: Always use foreach
when you need to go through every element in an array. It's cleaner and safer than a for
loop for this purpose.
Comparison Table: Key Differences
Loop Type | When to Use | Condition Check | Best For |
---|---|---|---|
while |
When you don’t know the number of iterations in advance. | Before executing the code block. | Reading files, database results until the end. |
do...while |
When the code must run at least once, regardless of the condition. | After executing the code block. | Input validation, menu systems. |
for |
When you know exactly how many times the loop should run. | Before executing the code block. | Iterating a specific number of times (e.g., 0 to 9). |
foreach |
Exclusively for iterating over arrays and objects. | Automatic, before each array element. | Looping through any type of array (indexed, associative). |
Important Loop Control Statements
Inside any loop, you can use these keywords to change the normal flow:
-
break
: Immediately exits the entire loop.for ($i = 0; $i < 10; $i++) { if ($i == 5) { break; // Stops the loop when $i is 5 } echo $i; } // Output: 01234
-
continue
: Skips the rest of the current iteration and jumps to the next one.for ($i = 0; $i < 5; $i++) { if ($i == 2) { continue; // Skips echo when $i is 2 } echo $i; } // Output: 0134
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.