In PHP, loops are essential for handling repetitive tasks such as sending emails to hundreds of users, processing input, doing calculations, and many more. They help you avoid redundancy in the code and help you write cleaner code faster and efficiently. PHP has several types of loops, like for loop, while loop, do while loop, and for-each loop. In this article, you will learn the working of these loops, along with when to use them. We will also explore some common mistakes beginners make when creating a logic for PHP loops.
Table of Contents:
What are Loops in PHP?
Loops are fundamental control structures in programming that repeatedly execute a block of code based on a specific condition. This condition is evaluated before or after each iteration, depending on the type of loop being used. As long as the condition returns true, the loop continues to run. Once the condition becomes false, the control exits the loop and continues with the rest of the program. Instead of writing the same line of code multiple times, a loop allows you to write it once and repeat its execution as needed. This automates repetitive tasks and reduces redundancy in code.
Why use Loops?
- Using loops avoids redundancy in code.
- It saves the time and effort of the developer.
- It makes the code easy to read and reduces the complexity.
- It allows for controlled execution of a block of code based on a specified condition.
Loops in PHP
There are various types of loops in PHP. They are the for loop, do while loop, while loop and foreach loop.
Loop Type |
Syntax |
Use Case |
Key Points |
for loop |
for (init; condition; increment) { } |
When: the number of iterations is known |
Controlled by: initialization, condition, and increment expressions |
while loop |
while (condition) { } |
When: loop runs based on a condition |
Entry-controlled: checks condition before each iteration |
do-while loop |
do { } while (condition); |
When: the loop must run at least once |
Exit-controlled: runs code block before checking condition |
foreach loop |
foreach ($array as $value) { } foreach ($array as $key => $value) { } |
When: iterating over arrays or collections |
Simplifies: array iteration; works with key-value pairs |
1. PHP For Loop
PHP For loop is used when you can quantify the execution of a block of code. To put it simply, when you know exactly how many times you want any block of code to repeat, you use a for loop.
A PHP for loop has three components or expressions that must be correctly defined for it to work without errors.
Syntax:
for (Initialization; Condition; Increment or Decrement ) {
// Code to be executed
}
- for: It is a keyword used to define a for loop.
- Initialization: This is an expression that sets the initial value that the loop variable takes.
- Condition: Based on this expression, a loop decides whether to go on or to stop
- Increment or Decrement: It changes the value of the loop variable after each iteration is finished. It keeps track of how many times the loop has run.
Flowchart:
Example:
Let us print “Hello Intellipaat!!!” seven times using a for loop in PHP.
Code:
<?php
for ($i = 0; $i < 7; $i++) {
echo "Hello Intellipaat!!!" . PHP_EOL;
}
?>
Output:
Explanation: In this example, we used the for loop. Every time a loop is executed, it completes one iteration. The $i variable gets incremented by one with each iteration. Since we added the condition $i < 7 and i started from 0, “Hello Intellipaat!!!” was printed 7 times.
2. PHP While Loop
A PHP while loop is an “entry-controlled” loop. It grants entry inside the loop if and only if the condition is evaluated to be true. In each iteration, it checks the condition. It has only one component other than the block of code.
Syntax:
while (condition) {
// Code is executed
}
- While: It is a keyword used to define a while loop.
- Condition: This is an expression which is checked every time at the start of the loop. This expression decides whether a particular iteration will run or not. The moment the condition becomes false, the control comes out of the loop and executes the next line of code.
Flowchart:
Example:
Let us take an example to explain the while loop in PHP. We will count down from 10 to 1 using a PHP while loop. We will use a $count variable that will store the count for the countdown. With each iteration, we will first display the current count using the echo function and then decrement the count variable using $count–. Once the count variable becomes zero, the condition $count > 0 will become false and the control will exit the loop.
<?php
$count = 10;
while ($count > 0) {
echo "Current count: ".$count. PHP_EOL;
$count--;
}
echo "Countdown complete!". PHP_EOL;
?>
Output:
Explanation: Here, using a while loop, we counted down from 10 to 1. We used the condition while($count>0), to run the loop until count variable becomes zero.
3. PHP Do while Loop
A PHP do-while loop is similar to the while loop. The only difference between the two is that the condition expression is validated at the end instead of checking it at the start, like in a while loop. This means that the first iteration of the do-while is guaranteed to run regardless of whether the condition evaluates to true or not.
Syntax:
do {
// code to be executed
} while (expression);
- do…while…: These keywords are used to define a do while loop
- expression: It is the condition that is checked when running the loop. If the expression evaluates false, then the control will come out of the loop and execute the rest of the program.
Flowchart:
Example:
Let us look at an example execution of a PHP do while loop. The condition expression that we use is $num < 5. When this condition becomes false, the loop will stop executing.
Code:
<?php
$num = 10;
do {
echo "This line is inside the do-while loop.". PHP_EOL;
echo "Current value of $num: " . $num . PHP_EOL;
$num++;
} while ($num < 5);
echo "This line is outside the do-while loop.". PHP_EOL;
?>
Output:
Explanation: In this example, $num starts at 10. Since $num < 5 is false, the loop runs once because a do while loop always executes the code before checking the condition. The loop stops after the first iteration.
Get 100% Hike!
Master Most in Demand Skills Now!
4. For each Loop in PHP
For each loop in PHP is primarily used to iterate over arrays or objects. This loop runs once for each element of an array or iterable until the last element. It also works with the key-value pairs in associative arrays. It has separate syntax for sequential values and for key-value pairs.
Syntax:
- Sequential Data Structure
foreach ($array as $value) {
// code block
}
- Key-value Pairs
foreach ($array as $key => $value) {
#code block
}
Example:
Let us look at an example to understand for each loop in PHP, where we print the name of the student and their marks from an associative array that has all the marks of students of a class.
Code:
<?php
$studentMarks = [
"Rahul" => 85,
"Priya" => 92,
"Amit" => 78,
"Sneha" => 65,
"Vikram" => 95
];
foreach ($studentMarks as $studentName => $marks) {
echo $studentName . ": " . $marks . PHP_EOL;
}
?>
Output:
Explanation: In this example, we have five elements inside the array. Therefore, the loop automatically ran for each element until it reached the end element.
Difference Between While Loop and Do While Loop in PHP
The difference between a while loop and a do while loop in PHP is the order of execution of code inside the loop. In the while loop, the condition expression is evaluated first before the code is executed, whereas in do while loop, the code inside the loop is executed once before the condition expression is evaluated. Let us look at this difference with the help of an example.
Code:
<?php
$num = 10;
echo "Using while loop:n";
while ($num < 5) {
echo "Inside while loopn";
}
echo "nUsing do-while loop:n";
$num = 10;
do {
echo "Inside do-while loopn";
} while ($num < 5);
?>
Output:
Explanation: In the PHP while loop, the condition $num < 5 is false, so the loop body does not execute even once. In the PHP do while loop, the loop body is executed once, even though $num < 5 is false, because the condition is evaluated after the first iteration.
Difference between for and for each loop in PHP
The difference between a for loop and a for each loop in PHP is that a for loop is used when you know how many times you want to iterate a given loop. It is used with a numeric range. Whereas a for loop in PHP is used to iterate over an array or object. A for each loop runs as many times as there are elements inside the array. Let us understand this difference with the help of an example.
Code:
<?php
$colors = ["red", "green", "blue"];
// Using for loop
echo "Using for loop:n";
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "n";
}
echo "n";
// Using foreach loop
echo "Using foreach loop:n";
foreach ($colors as $color) {
echo $color . "n";
}
?>
Output:
Explanation: As you can see, both loops gave the same output. The difference was that in the for loop we had to give a manual index $i, the whereas in for each loop the index was taken equal to the number of elements.
Common Mistakes and Edge Cases in PHP Loops
Using loops in your PHP code will save you a lot of time, but improper usage can result in bugs that are quite hard to decipher. Here, we have listed some common mistakes beginners tend to make when coding a loop in PHP.
1. Infinite Loops
This is one of the most common mistakes that beginner PHP developers make. They accidentally create an infinite loop. This usually happens when the loop condition is always true, which is caused by an incorrect loop condition or the increment or decrement step being missing or incorrect.
Fix: Always ensure that the loop condition will eventually evaluate to false.
2. Off-by-One Errors
These errors occur when you run a loop one more time than required or a few less times than were required. It happens due to incorrect use of comparison operators.
Fix: To fix this error, you first have to confirm if you want to include or exclude the end value and then choose the operator accordingly.
3. Modifying Arrays Inside a foreach Loop
Beginner PHP developers often unknowingly modify an array while iterating over it with foreach, which can lead to unexpected behavior. These modifications can be something like adding or removing elements.
Fix: You should avoid modifying the array structure inside foreach. Use a for loop or copy the array if modification is needed.
4. Incorrect Initialization in for Loop
A common mistake PHP developers make while using loops in PHP is misplacing or misinitializing the loop counter, which can cause loops to either never execute or behave incorrectly.
Fix: Double-check the start value, condition, and increment or decrement expressions.
Conclusion
In this article, we have understood different types of loops in PHP that can be used by developers to reduce time and redundancy in code. We have also learned that you can use a PHP for loop when you know exactly how many times you want to execute a block of code. A PHP while loop uses its condition as an entry check before each iteration. PHP do while loops can be used when you want a block of code to run at least once. Finally, the foreach loop can be used with an iterable data structure.
Mastering loops in PHP will help you become a faster programmer and write better code that others can understand as well. To learn more PHP programming concepts and become a PHP developer, you should read this blog.
PHP Loops – FAQs
Q1. What are PHP loops?
A PHP loop is used to repeat code blocks multiple times, such as for, while, do-while, and foreach loops.
Q2. What is loop and its types?
You can think of a loop as code that repeats until a condition is met. Common types are for, while, do-while, and foreach loops.
Q3. What is the full form of PHP?
PHP stands for Hypertext Preprocessor.
Q4. What is for loop with example?
You can use a for loop to run code a fixed number of times. Example: for($i=0; $i<5; $i++) { echo $i; }
Q5. What is a looping statement?
A looping statement to execute code repeatedly until a condition changes, enabling automation of repetitive tasks.