PHP Switch Case: 3 Online Demos with Break and Default case

PHP Switch Case: 3 Online Demos with Break and Default case

Introduction to PHP Switch Case

The Switch/case is a type of decision-making statement in PHP. Use PHP Switch/case statement option when you have many options and have to execute one of those.

You may Watch a short video of this Tutorial

See an example of switch case

This is helpful where you have to use long blocks of if..elseif..else code. For example, if you have to execute a different block of code for different days of the Week or Month etc.

Syntax of switch case PHP

Following is the syntax to use switch case statement:

You can see, the switch statement contains an expression which is evaluated against each case. Each case statement also contains a break statement which is explained below. The default section executes if none of the cases is true (see details in the last section).

Example of using PHP switch case

The following example uses the names of Weekdays in switch case and executes a block of code that turns out to be true.

Experience this example online

PHP break statement

You have to use the break statement in order to quit parser from the switch case statement. If you do not use the break statement, the code will keep on executing for the next cases.

As you use the break statement in a case block that evaluates as true, it will execute the statements in that block and exit the switch statement and execution will move to the next line of code out of switch statement.

See example below for what happens if you do not use a break statement in the above example.

Experience this example online

 The output will be: Its Tuesday today Its Wednesday today Its Thursday today Its Friday today Its Saturday today Its Sunday today

The Default case

In the above example, there is no chance that among all of the cases, none of the cases will be true. However, in many cases, there will be situations where all conditions/cases are false.

In the case of the If statement, we used the else statement. In Switch statement, we use the Default case. So the block of code inside the default case will be executed if all of the cases are false. See example below:

Example of using PHP default case

You can check by changing the variable name value from NY to IL, Al and then to some other to see the output. As you give some other value that does not exist in PHP switch cases then the default case block will be executed.