HOME HTML EDITOR C JAVA PHP

PHP Switch Statement

The switch statement is used to perform different actions based on different conditions. It is a more efficient way to compare the same variable against many different values compared to a long list of if...elseif statements.

1. How it Works

The expression is evaluated once. The value of the expression is then compared with the values of each case. If there is a match, the associated block of code is executed.

<?php
  $favcolor = "red";

  switch ($favcolor) {
    case "red":
      echo "Your favorite color is red!";
      break;
    case "blue":
      echo "Your favorite color is blue!";
      break;
    case "green":
      echo "Your favorite color is green!";
      break;
    default:
      echo "Your favorite color is neither red, blue, nor green!";
  }
?>

2. The break Keyword

The break statement is used to stop the code from automatically running into the next case. Without a break, PHP will continue executing the following cases even if they don't match.

3. The default Keyword

The default statement is used if no match is found. It acts like the final else in an if-else statement.

<?php
  $d = 7;

  switch ($d) {
    case 6:
      echo "Today is Saturday";
      break;
    case 0:
      echo "Today is Sunday";
      break;
    default:
      echo "Looking forward to the Weekend";
  }
?>
Tip: Using a switch statement can make your code much cleaner and easier to read when you have many different conditions based on a single variable.