PHP CHAPTER 16

PHP Switch

switch selects one block from several possible values.

📘

What is it?

switch selects one block from several possible values.

💡

Why do we use it?

It is useful when one expression has several known choices.

⚙️

How does it work?

PHP compares the switch expression with each case until a match is found.

🧩

Syntax

PHP Syntax
switch ($value) {
    case 1:
        // code
        break;
    default:
        // code
}
💻

Example

PHP Example
<?php

$day = 2;

switch ($day) {
    case 1:
        echo "Monday";
        break;
    case 2:
        echo "Tuesday";
        break;
    default:
        echo "Unknown";
}

?>
🔍

Example Explained

$day contains 2, so case 2 executes. break stops the switch.
🚀

More Examples

<?php $choice = "PHP"; switch ($choice) { case "PHP": echo "PHP Course"; break; case "Java": echo "Java Course"; break; default: echo "Other"; } ?>

⚠️ Important Rules

break prevents unwanted fall-through.

❌ Common Mistakes

Forgetting break or using incorrect case values.

🌍 Real-World Use

Menus, status codes and category selection.

📝 Practice Exercise

Create a course selection menu using switch.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →