PHP switch Statement

Summary: in this tutorial, you will learn how to use PHP switch statement that provides another way to execute a block of code conditionally.

Introduction to PHP switch statement

In addition to the if statement, PHP provides switch statement that allows you to execute a code block conditionally. PHP switch statement compares a variable or an expression against many different values and execute a code block based on the value it equals to.

The following illustrates the switch statement syntax:

Let’s examine the switch statement syntax in more detail:

  • First, you put a variable or expression that you want to test within parentheses after the switch keyword.
  • Second, inside the curly braces are multiple case constructs where you put the values you want to compare with the variable or expression. In case the value of the variable or expression matches the value in a case construct, the code block in the corresponding case construct will execute. If the value of the variable or expression does not match any value, the code block in the default construct will execute.
  • Third, the break statement is used in each case or default construct to exit the entire switch statement.

It is very important to understand that the switch statement is executed statement by statement therefore the order of  case constructs is very important. If the value of the variable match a value in a case construct, PHP will execute code block in that case construct and ends the switch statement because of the break statement.
php switch statement

PHP switch statement examples

Let’s take a look at the following example.

First, we got a random number from 0 to 3 and assigned it to $x variable. Then we compared the value of $x with 0, 1, 2 and 3 and displayed the corresponding message if $x is equal to one of these numbers.

In PHP, the switch statement also allows you to compare a variable and expression with many different string values. See the following example:

The break statement is put at the end of each case construct to exit the entire switch statement. If you want to perform an action when the variable or expression matches one of different values, you can make use of the break statement as follows:

If the $command is close or logout, the script will display the same message.

In this tutorial, we have shown you how to use PHP switch statement to control flow of code execution based on the value of a variable or expression.

  • Was this tutorial helpful ?
  • YesNo