PHP Switch

PHP Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

This is significantly cleaner than writing a long, repetitive chain of if...elseif...else statements when comparing the exact same variable against multiple values.


How it Works

  1. The switch expression is evaluated once.
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. The break keyword stops the execution inside the switch block.
  5. The default statement is used if no match is found.

Example

<?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!"; } ?>