PHP loops

PHP Loops – Complete Guide with Examples

Welcome to phponline.in, your trusted source to master PHP programming step by step.

In this chapter, we will cover one of the most powerful concepts in PHP — Loops.

Loops are essential in PHP because they help us execute a block of code repeatedly, reducing redundancy and improving performance.

From printing sequences of numbers to iterating over arrays and objects, loops are everywhere in real-world PHP projects like:

  • Login systems
  • Shopping carts
  • Data-driven dashboards
  • API processing
  • CMS development

Let’s dive deep into PHP loops with syntax, examples, real-world use cases, and best practices.


You will Learn

  1. Introduction to Loops in PHP
  2. Why Use Loops in PHP?
  3. Types of Loops in PHP
  4. The while Loop in PHP
  5. The do...while Loop
  6. The for Loop
  7. The foreach Loop
  8. Nested Loops in PHP
  9. Loop Control Statements (break, continue)
  10. Infinite Loops in PHP
  11. Using Loops with Arrays
  12. Using Loops with Associative Arrays
  13. Using Loops with Multidimensional Arrays
  14. Loops and Functions
  15. Loops in Real-World Applications
  16. Performance Considerations with Loops
  17. Best Practices for Writing PHP Loops
  18. PHP Loops vs Recursion
  19. Common Mistakes in Loops
  20. Alternative Syntax of Loops in PHP

1. Introduction to Loops in PHP

In programming, a loop is a control structure that allows you to execute a block of code multiple times automatically until a condition is false.

For example:

$count = 1;
while ($count <= 5) {
    echo "Count is: $count <br>";
    $count++;
}

Output:

Count is: 1  
Count is: 2  
Count is: 3  
Count is: 4  
Count is: 5  

2. Why Use Loops in PHP?

Imagine needing to display numbers 1 to 100. Without loops, you’d have to write 100 echo statements! Loops save time, reduce code length, and increase efficiency.

Real-world use cases:

  • Printing database records
  • Processing forms
  • Running batch operations
  • Displaying menus dynamically

3. Types of Loops in PHP

PHP provides four main loops:

  1. while loop
  2. do...while loop
  3. for loop
  4. foreach loop

Additionally, you can nest loops and use control statements to manage them.


4. PHP while Loop

Syntax:

while (condition) {
    // code to execute
}

Example:

$number = 1;
while ($number <= 5) {
    echo "Number: $number <br>";
    $number++;
}

5. PHP do…while Loop

Executes code at least once, then checks condition.

$number = 1;
do {
    echo "Number: $number <br>";
    $number++;
} while ($number <= 5);

6. PHP for Loop

Best when you know the number of iterations.

for ($i = 1; $i <= 5; $i++) {
    echo "Iteration: $i <br>";
}

7. PHP foreach Loop

Designed for arrays & collections.

$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
    echo "$fruit <br>";
}

With keys:

$users = ["id1" => "Alice", "id2" => "Bob"];
foreach ($users as $id => $name) {
    echo "$id => $name <br>";
}

8. Nested Loops in PHP

Loops inside loops.

for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        echo "($i, $j) ";
    }
    echo "<br>";
}

9. Loop Control Statements

  • break; → Exit loop early
  • continue; → Skip current iteration

Example:

for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) continue;
    echo "Number: $i <br>";
}

10. Infinite Loops in PHP

Dangerous but sometimes useful (e.g., daemon scripts).

while (true) {
    echo "Running...";
    break; // prevent actual infinite loop
}

11. Using Loops with Arrays

$numbers = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($numbers); $i++) {
    echo $numbers[$i] . "<br>";
}

12. Using Loops with Associative Arrays

$student = ["Name" => "John", "Age" => 20, "Grade" => "A"];
foreach ($student as $key => $value) {
    echo "$key: $value <br>";
}

13. Using Loops with Multidimensional Arrays

$students = [
    ["John", 20, "A"],
    ["Alice", 22, "B"],
    ["Bob", 19, "C"]
];

foreach ($students as $student) {
    foreach ($student as $detail) {
        echo $detail . " ";
    }
    echo "<br>";
}

14. Loops and Functions

You can use loops inside functions.

function printNumbers($limit) {
    for ($i = 1; $i <= $limit; $i++) {
        echo $i . " ";
    }
}
printNumbers(10);

15. Real-World Applications of PHP Loops

  • Generating tables dynamically
  • Reading database results
  • Processing API responses
  • Building pagination
  • Creating reports

16. Performance Considerations with Loops

  • Minimize calls to count() inside loops
  • Use foreach for arrays (faster)
  • Avoid unnecessary nesting

17. Best Practices for Writing Loops

  • Use descriptive variable names
  • Always define loop exit conditions
  • Keep loops optimized for performance

18. PHP Loops vs Recursion

Loops → Iterative
Recursion → Function calling itself

Loops are generally faster, recursion better for tree/graph problems.


19. Common Mistakes in Loops

  • Infinite loops due to missing increment
  • Off-by-one errors (<= vs <)
  • Overusing nested loops

20. Alternative Syntax in Loops

Great for embedding PHP in HTML.

<?php for ($i = 1; $i <= 5; $i++): ?>
    <p>Item <?= $i ?></p>
<?php endfor; ?>
PHP loops, PHP while loop, PHP for loop, PHP foreach loop, PHP do while loop, PHP nested loops, PHP control structures, PHP programming basics

Realted


Frequently Asked Questions (FAQ)

Q1: Which loop is best for arrays in PHP?
A: The foreach loop is best for arrays because it’s simple and efficient.

Q2: Can I break out of nested loops?
A: Yes, by using break 2; to exit two levels.

Q3: What is the difference between while and do...while?
A: while checks condition first, do...while executes at least once before checking.

Q4: Are infinite loops bad?
A: Yes, unless controlled (e.g., with break or in background workers).

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments