← Back to Chapters

PHP Nested Loop

? PHP Nested Loop

? Quick Overview

A nested loop is a loop inside another loop. In PHP, nested loops are used to handle complex repetitive tasks such as iterating over multi-dimensional arrays, generating patterns, or working with combinations of values.

? Key Concepts

  • One loop runs completely inside another loop
  • The inner loop executes fully for every outer loop iteration
  • Commonly used with tables, matrices, and patterns

⚙️ Syntax / Theory

? View Code Example
// Generic structure of a nested for loop
for (initialization; condition; increment) {
    for (initialization; condition; increment) {
        // inner loop logic
    }
}

? Code Example

? View Code Example
// Nested loop printing values of i and j
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        echo "i = $i, j = $j<br>";
    }
}
?>

? Live Output / Explanation

The outer for loop runs three times. For each iteration of the outer loop, the inner loop runs three times. This produces nine total combinations of $i and $j.

⚡ Interactive Visualizer

Adjust the sliders to see how the inner loop completes for every outer loop step.

 

? Interactive Understanding

Imagine a grid where rows represent $i and columns represent $j. Each cell is processed once by the inner loop for every row of the outer loop.

?️ Use Cases

  • Printing tables and matrices
  • Working with multi-dimensional arrays
  • Generating numeric or star patterns
  • Handling combinations and permutations

✅ Tips & Best Practices

  • Keep nested loops as simple as possible
  • Optimize inner loops for performance
  • Use meaningful variable names for clarity

? Try It Yourself

  • Create a file nested_loop.php
  • Write a nested loop that prints a 1–5 multiplication table
  • Modify loop limits to generate different patterns