PHP Switch Statement

The switch statement is a statement that lets you compare a variable with different values. It is kind of similar to the else if statement, the only difference is that the else if statement performs actions based on conditions. For example, you have a variable called $favourite_colour which has a value that might change based on the user's input, you can use the value of the variable $favourite_color to match any of the values of the case keyword in the switch statement.  If a match is found, it executes the block of code associated with the case keyword, if there's no match, it executes the block of code in the default keyword. You need to use the break keyword to stop the execution of the switch statement when it is done executing that block of code, if there is no break keyword, it executes every block of code in the switch statement until the last block.

PHP Switch Statement Example

  Do It Yourself

The example above finds a value that matches the value of a variable $favourite_colour and executes the block of code in the case keyword where the match was found.

What You Should Know at The End of This Lesson

  • You should know how the switch statement works.
  • You should know to compare and match values with the switch statement.