PHP Loops: Concepts, Syntax, and Use Cases

PHP-Loops-feature-image.jpg

The 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?

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 PHP 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. 
  • PHP loops also allows for the 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. It is basically a type of PHP loops.

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: 

For loop 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:

Output - For Loop

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 that 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:

while loop 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:

Output - While Loop

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 the 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 being 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 to false, then the control will come out of the loop and execute the rest of the program.

Flowchart:

do-while loop 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:

Output - Do-while loop

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:

  1. Sequential Data Structure
foreach ($array as $value) {
  // code block
}
  1. Key-value Pairs
foreach ($array as $key => $value) {
  #code block
}

Example:

Let us look at an example to understand for each loop in PHP works, 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:

Output - ForEach Loop

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.

Loop Control Statements in PHP

Loop control statements help you to control the flow of loops in PHP. Below are the loop control statements in PHP discussed briefly with an example:

1. break Statement

The break statement in PHP is used to exit a loop early when a certain condition is met. It immediately stops the loop and continues with the next block of code after the loop.

Syntax:

break;

Example: 

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i equals 5
}
echo $i . " ";
}
?>

Output: 

break statement in PHP

This PHP code uses a for loop to print numbers from 1 to 10, but it stops the loop when $i equals 5 using the break statement, so the output “1 2 3 4” is printed to the console.

2. continue Statement

The continue statement in PHP is used to skip the current iteration of a loop and jump to the next one. It is commonly used when a specific condition is met, and you want to skip executing the remaining code inside the loop for that iteration. This helps in controlling loop flow more precisely.

Syntax: 

continue;

Example:

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
continue; // Skip the rest of the loop when $i equals 5
}
echo $i . " ";
}
?>

Output:

continue statement in PHP

The above PHP loop prints numbers from 1 to 10, but skips 5 using the continue statement, which moves control to the next iteration without executing echo when $i == 5, and finally it prints to the console.

3. goto Statement

The goto statement in PHP is used to jump to another section in the program marked by a label. It helps in skipping specific parts of the code, though its usage is generally discouraged due to poor readability and maintenance issues.

Syntax:

goto label;

label:
// Code to execute

Example:

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
goto skip; // Jump to the label when $i equals 5
}
echo $i . " ";
}

skip:
echo "Skipped the rest of the loop when i was 5.";
?>

Output:

goto statement in PHP

This code prints numbers from 1 to 4, then jumps to the skip label when $i == 5, effectively exiting the loop and skipping further iterations, and finally, this result is printed to the console.

When to Use Which Loop

  • For Loop: You can use it when the number of iterations is known in advance. Also, it is ideal for counters or fixed repetitions.
  • While Loop: Use when you want to repeat a block until a condition becomes false. This loop in PHP is good for unknown iteration counts.
  • Do-While Loop: You can use it when there is a need that the code must run at least once before checking the condition.
  • Foreach Loop: Use when iterating over arrays or objects, and best for looping through collections without manual indexing.

Difference Between While Loop and Do While Loop in PHP

Here is a comparison table that shows the difference between the while loop and do while loop in PHP:

Aspect while Loop do-while Loop
Condition Check Before the loop body After the loop body
Minimum Executions May not run at all if the condition is false Runs at least once, even if the condition is false
Syntax while (condition) { //code } do { //code } while (condition);
Use Case When you want to run code only if a condition is true When it should run once, regardless of the condition
Example Output (false condition) No output Executes once and shows output
Control Type Entry-controlled loop Exit-controlled loop

Now, let’s understand the main difference between these PHP loops with the help of an example.

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.

Example:

<?php
$num = 10;

echo "Using while loop:\n";
while ($num < 5) {
echo "Inside while loop\n";
}

echo "\nUsing do-while loop:\n";
$num = 10;
do {
echo "Inside do-while loop\n";
} while ($num < 5);
?>

Output:

Output - While loop vs Do-while loop in PHP

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

Here is a comparison table that shows the difference between the for and foreach loop in PHP:

Aspect for Loop foreach Loop
Use Case Used when the number of iterations is known Used to iterate over arrays or objects
Syntax for (init; condition; increment) { //code } foreach ($array as $value) { //code }
Works With Numeric values, counters Arrays and associative arrays
Manual Indexing Yes, you manually handle the index No need to manage the index, it’s handled automatically
Flexibility More flexible, suitable for complex iterations Simple and clean for array iteration
Best For Iterating a block a fixed number of times Looping through each item in an array

Now, let’s understand the main difference between these two PHP loops with the help of an example.

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.

Example:

<?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:

Output - Difference between for loop and for each loop in PHP

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, whereas in the for each loop the index was set equal to the number of elements.

PHP Loops Use Cases in Real Applications

  • Displaying Data from a Database: PHP loops are used to fetch and display rows from a database table using while or foreach.
  • Form Processing: When handling multiple input fields (like checkboxes or file uploads), loops help process each input item.
  • Generating HTML Elements Dynamically: You can use PHP loops to create dropdowns, tables, or lists based on data arrays.
  • Pagination: Loops are used to create numbered links for navigating through paginated results.
  • Calculations or Summations: Loops help calculate totals, averages, or apply formulas to a series of numbers.
  • Validating Multiple Fields: You should use PHP loops to check each input field against validation rules.

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 fewer times than required. It happens due to the 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 the 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 PHP loops 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.

Performance Tips and Best Practices for using PHP loops

  1. Use foreach for arrays – It is simpler and faster than for when working with arrays.
  2. Don’t call functions in loop conditions – Store results like count($array) in a variable before the loop to save time.
  3. Break early if needed – You should use a break to stop the loop once your task is done.
  4. Avoid changing arrays inside a foreach loop – Also, if you modify an array while looping over it can cause bugs.
  5. Keep loops simple – Try not to use loops inside loops unless necessary, because it will slow things down.
  6. Move constant values outside the loop – Don’t repeat the same calculation or value assignment inside every loop cycle.

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 PHP loops 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?

The PHP loops are 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.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner