PHP switch case Statement
October 25, 2018

PHP switch case statement Use to select one of many blocks of code to be executed.switch-case statement is alternative of the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.
Syntax of switch case statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
switch (n) { case case1: code to be executed if n=case1; break; case case2: code to be executed if n=case2; break; case case3: code to be executed if n=case3; break; default: code to be executed if n is different from all cases; } |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $favcolor = "Feb"; switch ($favcolor) { case "Jan": echo "This month is Jan"; break; case "Feb": echo "This month is Feb"; break; case "March": echo "This month is March"; break; default: echo "This is default case "; } ?> |
switch case statement excutes line by line thats why its different form if else statement in php. switch statement executes line by line and once PHP finds a case statement that evaluates to true, it’s not only executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of the switch block automatically. Read more about Php Knowledge
we add a break statement to the end of each case block. break statement tells PHP to break out execution when conditions meet.