PHP Switch

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.


variable PHP variable name which will be checked against case value.

If the given variable is equal to value_1, then the php code will be executed and the break is optional, used to terminate the switch block.

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

Run the above example

Example 2

Run the above example

Example 3

Run the above example

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *