PHP Switch Case : PHP Switch statement is very similar to a series of if..elseif statements but with a slight difference. It is used in a condition where using the
if.. elseif statement would be a lengthy approach, so instead of that PHP Switch case can be used.
Suppose there is a variable whose value will decide a certain kind of action, let's say the variable holds a number from
1 to 9. And according to the value in the variable, the program has to print the number in words, like,
1 in One, 2 in Two, and so on till 9.
So, one approach is to use the if..elseif statement, but it will increase the number of comparisons, that may slow down the program. If the variable has 9, then the if..elseif statement will have to compare all the 9
'if' conditions to get to a result and print 'Nine'. But if we use PHP Switch statement then only one condition will be checked and that's it.
PHP Switch Case uses
'case', each case has a different set of instructions associated with it, written by the programmer. When PHP Switch case checks the condition then it jumps to the appropriate case, skipping all other cases before that, and executes it.
So when you have to compare the same variable for different values, and each value is associated with a different set of code, then use the Switch statement. Look at the syntax and the example below to see how the PHP Switch statement works.
In the example above, there is a use of a
break statement that might have confused you. A break statement is used to terminate or break the flow of the switch statement. If the Switch statement finds a matched case then it will not only execute that particular case but all the cases after that. So, to stop this execution flow of the Switch case, we use break statements after each case to stop the execution of other cases.
Try removing the break statement from the program and then execute it, you will notice the difference.
Default statement is used inside the PHP Switch Statement in case of no match. Suppose any of the provided cases doesn't match with the value of the variable then the default statement will be executed. Although the default statement is usually written at the end of the Switch statement, it can be written anywhere inside.