PHP Switch Case Conditional Statement With Example

PHP Switch Case Statement

PHP Switch case statement perform a test and execute a piece of code if it finds the exact match of the test result. There many cases that contain some blocks of codes which gets executed according to the exact match.

Syntax

The syntax of the switch statement contains the multiple numbers of cases and a default state which is you can use. The default case is not necessary to add inside the switch case. However, if you want to execute a block of code only if all the cases not matching with the condition or result.

PHP Switch Case Statement Examples

Let us take few examples which can help you to increase your understanding of PHP switch statement. Learn each example to use switch correctly.

PHP switch case statement without default case

This example contains the switch statement without the default statement inside.
Example 1:

Output

The student is brilliant study.

The example contains the variable $result which switch statement matches with all the case if it matches. If the case matches with the variable, it will execute the block of code inside the matching case.

PHP switch case statement with default case

The below-given example showing the switch cases with the default statement which will execute only if all cases not matching with the condition.

Example 2:

Output

You are not from any of these countries.

The example contains a variable $result which will not match with any cases and because of this, the block of code inside the default statement will get executed.

Don’t forget to add the break statement after each case. If you do not add the break statement, the output will execute both the matched case code and the block of code inside the default statement.

Difference between PHP switch case and PHP if elseif

PHP if statement evaluates the condition and the result if true and if the result is true it executes the code. But in the switch statement, you match the result with some predefined values arranged sequentially in cases. You need to put the break work after each case, if you do not put the break, PHP parse the next case and the other also.

If you are a beginner in PHP, that always put a break after each case to remove any confusion with the switch case statement result.

Switch statement contains a default statement also which execute only when the condition does not match with the case statements. This is similar to the else of the if else statement. But one thing you should notice here that if you do not put the break work after each case, switch statement also executes the default with the matched case you will get the two code execution after switch statement. So, always put break work after each case.

You must also read:

Resource