

So, always put break work after each case. This tutorial will touch on how to write a switch statement in PHP and cover some of the basics that you need to know. The switch-case statement tests a variable. The following two examples are two different.
Php switch case tutorial code#
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. The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch statement is similar to a series of if statements on the same expression. This is similar to the else of the if else statement. Switch statement contains a default statement also which execute only when the condition does not match with the case statements. Note that the so-called body of a case label need not be made a compound statement the set of statements associated with a particular case label ends with a.

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. Put those many values into an array and query the array, as the switch-case seems to hide the underlying semantics of what you're trying to achieve when a string variable is used as the condition, making it harder to read and understand, e.g. 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. The switch-case statement condition its tests a variable against a series of values until it finds a match, after that executes the block of code corresponding to that match. But in the switch statement, you match the result with some predefined values arranged sequentially in cases. Here, The switch-case statement is an alternative method to the if-elseif-else statement or Condition, which are the almost same thing. PHP if statement evaluates the condition and the result if true and if the result is true it executes the code. Difference between PHP switch case and PHP if elseif 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. 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.ĭon’t forget to add the break statement after each case.
