Login | Contact Us | Site Map | Resources

PHP Conditions & Loops

Home > PHP Tutorial > Switch

Switch

Sometimes, multiple if/elseif/elseif statements are just not the most efficient option when checking for a specific condition. The switch statement can replace multiple if/elseif/elseif statements when you want to determine whether or not one value is equal to one of many other values in a more efficient manner.

The switch statement begins by accepting a single value, which it compares against multiple cases. When the case, or condition, is met (true), the specified block of code is executed, and the remainder of the switch statement is skipped.

<?php
  $time = "3 A.M.";
  switch ($time) {
    case "3 P.M.":
      echo "Good afternoon!";
      break;
    case "9 P.M.":
      echo "Good evening!";
      break;
    case "3 A.M.":
      echo "Good night!";
      break;
    case "9 A.M.":
      echo "Good morning!";
      break;
    default:
      echo "Hello!";
      break;
  }
?>

In our example, we begin by providing the switch statement with a value in the form of a variable. That value is compared against multiple cases, each of which contain their own value and end with a full colon rather than the standard semi-colon.

The switch statement accepts multiple lines of code in each block of code following each case, however our example only has a single line of code that should be run in the event that the case (condition) is true. Each block ends with a break to indicate that the remainder of the switch statement should be skipped after the case is true and the associated block of code is run.

The "default:" portion of the switch statement is similar to the else clause used with if statements. It determines what is to be done if none of the cases are true.

So do you know what the result of our switch statement is yet?

Good night!