0
0
PHPprogramming~15 mins

Break statement with levels in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Break Statement with Levels in PHP
📖 Scenario: Imagine you are managing a small library system. You want to check shelves and books to find a specific book. Once found, you want to stop checking further shelves and books immediately.
🎯 Goal: You will create nested loops to simulate shelves and books. Then, you will use the break statement with levels to stop the loops once the book is found.
📋 What You'll Learn
Create two nested for loops: outer loop for shelves (1 to 3), inner loop for books (1 to 5).
Create a variable targetBook with the value 3 to represent the book to find.
Use break 2; to exit both loops when the target book is found.
Print a message showing which shelf and book was found.
💡 Why This Matters
🌍 Real World
Nested loops and breaking out of them are common when searching through multi-level data like shelves and books, menus and submenus, or rows and columns.
💼 Career
Understanding how to control loops with break levels helps in writing efficient code for data processing, web scraping, and game development.
Progress0 / 4 steps
1
Create nested loops for shelves and books
Create a for loop with variable $shelf from 1 to 3 and inside it create another for loop with variable $book from 1 to 5.
PHP
Need a hint?

Use two for loops, one inside the other, with the variables $shelf and $book.

2
Add a target book variable
Create a variable called $targetBook and set it to 3 before the loops.
PHP
Need a hint?

Define $targetBook before the loops to know which book to find.

3
Use break with levels to stop loops when book is found
Inside the inner loop, add an if statement to check if $book equals $targetBook. If yes, use break 2; to exit both loops.
PHP
Need a hint?

Use break 2; to stop both loops when the target book is found.

4
Print the shelf and book found
After the loops, write a print statement to display: "Found book $targetBook on shelf $shelf".
PHP
Need a hint?

Use print to show the message with the variables $targetBook and $shelf.