learn

Switch Case

category: Basics
Created by: Dr.Ferrous

Switch Case

category: Basics
Created by: Dr.Ferrous
twitter google+ facebook pin 

Switch is another type of conditional, best used in place of a long if-elseif-else conditional.
Switch statement selects one of many blocks of code to be executed, by comparing the value of a single variable with a succession of values.

Syntax:

The value of the $variable within the brackets is the item being tested.

The switch conditional compares the value of $variable with the values for each case. When it finds a match, the block of code associated with that case is executed, up until the break. If no match is found, the default statement is executed, assuming it exists (it's optional).


The switch conditional can only check a variable's value for equality.

The break statements are optional, but if you don't use them, PHP will continue to evaluate the next case and may execute some code further down the case tree. The default statement is used if no match is found.

Example:

This code will output: "Medium number".

 

Another example, with a string as the value to be compared.