The PHP switch statement is similar to multiple if statement. It will execute the block of code in the different scenario like if statement. Compared to if
statement, switch
is more readable and maintainable for the multi-level control statement.
Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
switch (variable) { case value_1: php code; break; case value_2: php code; break; case value_3: php code; break; ... default: php code; } |
variable |
PHP variable name which will be checked against case value. |
value_1 |
If the given variable is equal to value_1, then the php code will be executed and the Note: Like case value_1, we can use value_2 and value_3, etc., when the case value is equal to switch variable, the corresponding block of php code will be executed. |
default |
This is the default block of code for switch, if the given variable is not matched with any case values, then this block of code will be executed. |
Consider the following 3 examples. In the example 1, we have declared the variable as ‘apple’, which will be checked against the switch cases. The variable ‘apple’ is matched with first case ‘apple’ and so the PHP code belonging to this block will be executed, so the output is ‘i ate apple’.
In the example 2, the output is ‘i ate mango’. This is working same like example 1.
In the example 3, we have declared the variable as ‘fruits’, which is not matched any of cases, so the default block will be executed. In this example the output is ‘i will yet to eat apple or mango’.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $variable = 'apple'; switch($variable) { case 'apple': echo 'i ate apple'; break; case 'mango': echo 'i ate mango'; break; default: echo 'i will yet to eat apple or mango'; break; } ?> |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $variable = 'mango'; switch($variable) { case 'apple': echo 'i ate apple'; break; case 'mango': echo 'i ate mango'; break; default: echo 'i will yet to eat apple or mango'; break; } ?> |
Example 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $variable = 'fruits'; switch($variable) { case 'apple': echo 'i ate apple'; break; case 'mango': echo 'i ate mango'; break; default: echo 'i will yet to eat apple or mango'; break; } ?> |