Another way of using a Switch

Sheetal Kabra
2 min readMay 8, 2021

--

You might have already been using a switch case in a conventional manner where you pass a parameter and get the result on the basis of what case statement parameter value will match as below, but there is more to switch, you can use multiple conditions inside a switch statement. huh? let’s see that.

Output: Saturday, let’s try something new in cooking.

Now let’s try another way:

  1. Using ‘AND’ in switch case condition in PHP:

Output: The price per unit will be $16

2. Using ‘OR’ in switch case condition in PHP:

Output: The color will be red

Notice that in the above example we have used true rather than $unit or $fruit in the switch. so that it can execute a case statement which is a boolean expression.

So you can experiment with any boolean expression combination in the case and make your if-else ladder more readable with this method.

let’s try with yet another example. though not a very real world and great example but it meets the objective of the illustration

Output: date is in between 1 to 10

Do you think is there any flaw in this?

Here, in the above example, we are mixing two values in a single switch which will cause a clash, suppose the domain of fruit got increased and we added one more fruit but we miss adding this to the case, in this case, the fruit switch would be skipped and it will move in the day flow. the default case of fruit doesn’t match never gets executed. The issue here is the code of block is not having a single responsibility.

Final thoughts:

1. We can use AND OR conditions in the switch, but we need to be careful in the way we decide the cases, the cases are not limited to a specific domain anymore, any boolean value can be a case here.

2. Break is compulsory in switch, if we are not using break, it runs all the cases(whether it is true or false) after any case condition is true. This is true for any Switch but this is a common error which programmer gets into while using Switch statements.

Hope you may get another way of using the switch and please do comment with your scenario in case you use this kind of flow.

--

--