0
0
PHPprogramming~5 mins

Nested loop execution in PHP

Choose your learning style9 modes available
Introduction

Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.

When you want to print a multiplication table.
When you need to check every pair of items in two lists.
When you want to create a grid of rows and columns.
When you want to compare each element with every other element.
When you want to generate combinations of items.
Syntax
PHP
<?php
for (initialization; condition; increment) {
    for (initialization; condition; increment) {
        // code to repeat
    }
}
?>
The inner loop runs completely every time the outer loop runs once.
Use different variable names for each loop counter to avoid confusion.
Examples
This prints pairs of numbers where the first number goes from 1 to 3 and the second from 1 to 2.
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        echo "$i,$j\n";
    }
}
?>
This prints a 2 by 3 grid of stars.
PHP
<?php
for ($row = 1; $row <= 2; $row++) {
    for ($col = 1; $col <= 3; $col++) {
        echo "*";
    }
    echo "\n";
}
?>
Sample Program

This program prints a 3 by 3 multiplication grid. Each row shows multiples of the row number.

PHP
<?php
// Print a 3x3 grid of numbers
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        echo $i * $j . " ";
    }
    echo "\n";
}
?>
OutputSuccess
Important Notes

Remember to add a newline after the inner loop to separate rows.

Nested loops can slow down your program if they run many times, so use them carefully.

Summary

Nested loops run one loop inside another to handle repeated tasks in layers.

The inner loop finishes all its cycles for each single cycle of the outer loop.

They are useful for working with tables, grids, and pairs of data.