9) PHP Switch statement

Basic structure of a switch statement

The Case is same as if the value is true and a default is same as else. You can either use if/elseif or switch statements. But generally, switch statement are easier to read when you put more conditions.

Example switch

The first case is only compared against one case and the second string is displayed if any of the three case match “Kritika Shrivastava” or “kk” or “Devesh Shrivastava”. If nothing matches default will be executed. When a statement matches, then the string is executed and the statement breaks and everything else is ignored.

We can use switch statement like this with “number”, “string” or “boolean”.
For using comparison operator in the switch statement we need to tweak your code like

You need to add complete expression $cost < 99 for using comparison operator.

Exercise: Run the code above. Try using different values of $name and check the output. Check what happens if you forget to add break.

Note: If you forget to add break then even if the condition matches all other conditions will also be executed.