← Back to Chapters

PHP Switch Statement

? PHP Switch Statement

? Quick Overview

The switch statement in PHP is used to perform different actions based on different conditions. It works as a cleaner and more readable alternative to multiple if...elseif statements when evaluating the same variable.

? Key Concepts

  • Evaluates one expression against multiple values
  • Uses case labels for matching
  • break prevents fall-through
  • default handles unmatched cases

⚙️ Syntax / Theory

? View Code Example
// Basic syntax of PHP switch statement
<?php
switch (expression) {
case value1:
echo "Matched value1";
break;
case value2:
echo "Matched value2";
break;
default:
echo "No match found";
}
?>

? Code Example

? View Code Example
// Switch statement example using days
<?php
$day = "Tuesday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Tuesday":
echo "Second day!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "Just another day.";
}
?>

? Live Output / Explanation

The variable $day is compared against each case. When the value matches "Tuesday", the corresponding message is printed and execution stops due to the break statement.

? Interactive Playground

Change the value of $day below to see how the switch statement reacts!

> Output: Second day!

? Interactive Idea

You can dynamically change the value of $day and reload the PHP file to observe how different cases are triggered based on the input.

? Use Cases

  • Menu selection systems
  • Role-based access handling
  • Day, month, or status mapping
  • Simple decision-making logic

✅ Tips & Best Practices

  • Use switch when comparing a single variable
  • Always include a default case
  • Remember to add break after each case

? Try It Yourself

  • Create a file named switch_example.php
  • Define a variable $fruit with different values
  • Use switch to display messages for each fruit