📖 Scenario: You are organizing a small event and want to print a seating chart. There are 3 rows and each row has 4 seats. You want to list each seat by its row and seat number.
🎯 Goal: Create a PHP program that uses nested loops to print each seat as "Row X Seat Y" for all rows and seats.
📋 What You'll Learn
Create a variable $rows with the value 3
Create a variable $seats_per_row with the value 4
Use a nested for loop where the outer loop uses $row from 1 to $rows
The inner loop uses $seat from 1 to $seats_per_row
Print each seat as Row X Seat Y where X is the row number and Y is the seat number
💡 Why This Matters
🌍 Real World
Nested loops are useful when you need to work with tables, grids, or any data with rows and columns, like seating charts or calendars.
💼 Career
Understanding nested loops is important for programming tasks involving multi-dimensional data, such as processing images, spreadsheets, or game boards.
Progress0 / 4 steps
1
Create variables for rows and seats
Create a variable called $rows and set it to 3. Create another variable called $seats_per_row and set it to 4.
PHP
Hint
Use $rows = 3; and $seats_per_row = 4; to create the variables.
2
Set up the outer loop for rows
Add a for loop that uses the variable $row starting from 1 up to and including $rows.
PHP
Hint
Use for ($row = 1; $row <= $rows; $row++) to loop through rows.
3
Add the inner loop for seats
Inside the for loop for $row, add another for loop that uses the variable $seat starting from 1 up to and including $seats_per_row.
PHP
Hint
Use for ($seat = 1; $seat <= $seats_per_row; $seat++) inside the outer loop.
4
Print each seat label
Inside the inner for loop, print the text Row X Seat Y where X is the value of $row and Y is the value of $seat. Use echo and add a newline after each print.
PHP
Hint
Use echo "Row $row Seat $seat\n"; to print each seat with a newline.
Practice
(1/5)
1. What happens when a nested loop runs in PHP? for ($i = 0; $i < 2; $i++) { for ($j = 0; $j < 3; $j++) { // code } }
easy
A. The inner loop runs completely for each iteration of the outer loop.
B. The outer loop runs completely for each iteration of the inner loop.
C. Both loops run only once.
D. The loops run simultaneously without nesting.
Solution
Step 1: Understand loop nesting order
The outer loop runs from 0 to 1 (2 times). For each outer loop iteration, the inner loop runs fully.
Step 2: Inner loop completes all cycles per outer iteration
For each $i, $j runs from 0 to 2 (3 times), completing all inner cycles before next outer iteration.
Final Answer:
The inner loop runs completely for each iteration of the outer loop. -> Option A