switch is similar with multiple if structure.
Sometimes you want to compare same expression with different multiple values, and execute a different statements depending on value. This can be done using switch statement.

How switch work

A switch structure execute line by line. If the case value matches the value of switch expression then only the statements will execute.
In a switch statement, the condition is evaluated only once and the result is compared to each case statement.

Syntax of switch


Flowchart of switch


Example of switch –


PHP continues to execute the statements until the end of the switch block, or it sees a break statement.
If there is no break keyword at end of case’s statements, PHP will execute the statements of the following case.
For example:



Switch case can be a string. For example


case statement can be empty, which simply passes control to next case statement.
For example:


Default case is a special case. If any case value wasn’t matched with switch expression result then default case will execute.

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.