Switch is a conditional statement: use it run different blocks of code, depending upon a specified value.


$n = 2;
switch (n)
case 1:
  print 'One';
case 2:
  print 'Two';
  print 'Neither one nor two';
  • Begin with the keyword switch
  • Use parentheses to enclose a value; this key value will decide which code to run.
  • Use a pair of curly braces {} to form a code block. (Code blocks are not followed by semicolons.)
  • Inside the code block, use the case keyword, followed by a case value and then a colon, followed by one or more lines of code
  • If the case value matches the key value, this code will run.
  • Use the break statement (followed by a semicolon) to indicate the end of the case statement.
  • If the first case value does not match the key value, PHP checks the next case, and so on.
  • Use the default: clause to indicate code which will run if none of the above cases match.