A loop in PHP helps you run tasks without repeating the same lines. In this article, you will learn how loops work in PHP and how to use its types. Let’s get started.
Table of Content
Understand the Loop in PHP
You can run a block of code multiple times using loops in PHP. This lets you follow steps until a condition becomes true.
You don’t need to repeat a task ten times. Write it once and run it multiple times with a loop.
Loops can run a fixed number of times or until a condition changes.
For example:
You might loop through users in a database or count from 1 to 10.
Here are the types of loops in PHP:
- for loop
- while loop
- do…while loop
- foreach loop
So, how does the loop work in PHP?
A loop runs a block of code over and over. It checks a condition each time. The loop runs again when the condition is true. When the condition is false, the loop stops.
This design gives you control over how many times the code runs. You can use variables to count or move through arrays.
You should avoid loops when you can use built-in functions such as array_map or whatever. Loops can slow your code if you do not manage them well.
Avoid loops with conditions that never change, or you will create infinite loops. Do not use loops for simple tasks that do not need repetition.
Types of Loops in PHP
The for Loop:
The for loop executes a block of code a specific number of times. It uses three parts:
- Start value.
- Test condition.
- Increment or decrement.
Here is an example:
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}It prints:
1 2 3 4 5
This loop starts at 1. It runs while $i is 5 or less and adds 1 each time.
The while Loop:
The while loop runs while a condition remains true. It checks the condition before each run. The loop stops when the condition is false.
For example:
$i = 1;
while ($i <= 3) {
echo $i . " ";
$i++;
}It runs until $i is greater than 3.
The do…while Loop:
The do…while loop runs the block once first. After that, it checks the condition. It repeats the block if the condition is true.
For example:
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 2);It prints:
1 2
This ensures the code runs at least once.
The foreach Loop:
The foreach loop works with arrays. It runs once for each item. For example:
$colors = ['red', 'blue', 'green'];
foreach ($colors as $color) {
echo $color . " ";
}The output:
red blue green
It shows you all items in an array.
You can stop a loop early with the break statement. For example:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo $i . " ";
}It prints:
1 2
It stops when $i is 3.
Nested Loops in PHP
Nested loops are loops inside other loops. You use them for grids, tables, or multi-level data.
Here is an example that prints a number grid:
for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i,$j ";
}
}Here is the output:
1,1 1,2 1,3 2,1 2,2 2,3
The outer loop runs twice. The inner loop runs three times for each outer loop.
Another example of a star pattern:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "*";
}
echo "\n";
}Output:
*
**
***
Each row has one more star.
Table with data:
$rows = 2;
$cols = 2;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $cols; $j++) {
echo "Cell($i,$j) ";
}
echo "\n";
}Output:
Cell(1,1) Cell(1,2)
Cell(2,1) Cell(2,2)
This creates a simple table with labeled cells.
Loop Control with Conditional Statements
Conditional statements guide what happens in a loop. You can use if and continue inside loops to control flow.
Skip values:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . " ";
}Output:
1 2 4 5
The continue skips the code for 3.
Stop on condition:
$numbers = [2, 4, 6, 8, 10];
foreach ($numbers as $num) {
if ($num > 6) {
break;
}
echo $num . " ";
}Here is the output:
2 4 6
The break statement stops when the number is greater than 6.
Examples 3: Even numbers only:
$i = 1;
while ($i <= 6) {
if ($i % 2 != 0) {
$i++;
continue;
}
echo $i . " ";
$i++;
}The output:
2 4 6
This prints even numbers only.
Alternative Iteration Methods
PHP gives you multiple ways to loop over arrays or collections. You can use array functions or generators.
Array functions like array_map run a callback on each element and return a new array.
$nums = [1, 2, 3];
$squares = array_map(function($n) {
return $n * $n;
}, $nums);
print_r($squares);This code squares each number in the $nums array and prints the results.
You can use the array_filter when you want to skip elements or filter data. It keeps only items that meet a condition.
While generators give you another way, they yield one value at a time rather than build a full list first.
Here is an example:
function countToFive() {
for ($i = 1; $i <= 5; $i++) {
yield $i;
}
}
foreach (countToFive() as $num) {
echo $num, PHP_EOL;
}This produces numbers from one to five. The loop reads each value one by one.
SPL iterators like RecursiveIteratorIterator let you iterate through nested arrays or objects.
$data = [1, 2, [3, 4]];
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach ($rit as $value) {
echo $value, PHP_EOL;
}This code takes every value. That includes those inside nested arrays, and prints them line by line.
Interaction of Loops with Functions and Classes
Loops work with functions and classes in PHP. The foreach loops can process arrays or any object that implements Traversable. While the classes can define custom iteration through iterator interfaces.
Functions can declare parameters as iterable to accept arrays or traversable objects without conversion.
You must unset the reference variable after the loop when you use references in foreach. Or it may cause problems later.
$items = [1, 2, 3];
foreach ($items as &$item) {
$item *= 2;
}
unset($item);
print_r($items);This code doubles each item in the array by using a reference. Then it unsets $item to avoid errors from leftover references.
Classes can have generator methods to make lazy streams you can use step-by-step.
class Numbers {
public function getStream(): iterable {
for ($i = 0; $i < 3; $i++) {
yield $i * 10;
}
}
}
foreach ((new Numbers())->getStream() as $value) {
echo $value, PHP_EOL;
}This class method yields values one at a time. The loop receives and prints them as they arrive.
Use iterable type hints in your functions to accept both arrays and objects uniformly.
Examples of PHP Loops
Count from 1 to 3:
for ($i = 1; $i <= 3; $i++) {
echo $i . " ";
}The output:
1 2 3
This loop begins at $i = 1 and keeps going as long as $i is 3 or less. In each round, it prints out the current $i followed by a space. Then, it adds 1 to $i. So, the result you see is 1 2 3.
List array items:
$fruits = ['apple', 'banana'];
foreach ($fruits as $fruit) {
echo $fruit . " ";
}The output:
apple banana
This code makes an array named $fruits that holds apple and banana. The foreach loop looks at every item and saves it in $fruit. Then, it prints each fruit with a space after it. The output you get is apple banana.
While loop countdown:
$i = 3;
while ($i > 0) {
echo $i . " ";
$i--;
}The output:
3 2 1
Here, the code sets $i to 3. The while loop runs as long as $i is more than 0. It prints the value and then subtracts 1, so the output is 3 2 1 .
Nested number grid:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i$j ";
}
}Output:
11 12 13 21 22 23 31 32 33
This code has two for loops, one inside the other. The first loop sets $i from 1 to 3. For each $i, the second loop sets $j from 1 to 3. It prints each pair as ij, showing all combinations.
Filter even numbers in the array:
$nums = [1, 2, 3, 4, 5, 6];
foreach ($nums as $num) {
if ($num % 2 != 0) {
continue;
}
echo $num . " ";
}Output:
2 4 6
This code makes an array with numbers from 1 to 6. The foreach loop looks at each number. If the number is odd, it skips to the next one. It only prints the even numbers.
Wrapping Up
In this article, you learned many topics, such as
- What a loop in PHP is
- How it works, when to avoid it
- Types of loops
- Nested loops
- How to control loops with conditions.
Here is a quick recap:
- Loops repeat tasks without extra code.
- Types include for, while, do…while, and foreach.
- You can use break and continue to control loops.
- Nested loops help with grids and tables.
FAQs
What is the difference between for loop and while loop in PHP?
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
This prints: 1 2 3 4 5
A while loop runs while a condition is true. It checks the condition before each run.
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
This also prints: 1 2 3 4 5
How does foreach loop work in PHP?
$colors = ['red', 'green', 'blue'];
foreach ($colors as $color) {
echo $color . " ";
}
This prints: red green blue
What do break and continue do in loops?
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo $i . " ";
}
Prints: 1 2
continue skips one loop cycle.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . " ";
}
Prints: 1 2 4 5
How do nested loops work in PHP?
for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i,$j ";
}
}
Prints: 1,1 1,2 1,3 2,1 2,2 2,3
Similar Reads
PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match. Understand…
The array_pop function in PHP gives you a direct way to take the last element from an array. Understand the…
The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…
PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…
PHP static method lets you call functions without an object. In this article, we will cover the following topics: The…
PHP array_unshift helps you add new elements to appear before the existing ones. Understand the array_unshift function in PHP The…
Sorting data is one of those things we do all the time but rarely stop to think about. Whether you…
PHP $_SERVER is a superglobal. It’s a predefined variable containing information about your server, client, and request environment. As a…
You can assign the boolean data type to PHP variables or use it as a direct value. This enables you…
The array_key_first helps you to get the first key of an array directly in PHP. It saves time and removes…