In its standard form, the SWITCH function provides alternations depending on the set condition, very similar to IF. The main advantage seems to be that the structure is easier to analyze.
1 2 3 4 5 6 7 8 9 10 11 |
$variab="ceva"; SWITCH($variab) { CASE sit_1: // if $variab is equal to the sit_1 condition ECHO... or $val=...; BREAK; CASE sit_2: // dif $variab is equal to the sit_2 condition ECHO... or $val=...; BREAK; DEFAULT: // if $variab does not meet the previous conditions ECHO... or $val=...; } |
Equivalence by IF
As I mentioned, the equivalent can be achieved using the IF function.
1 2 3 4 5 6 7 8 9 10 11 12 |
IF ($variab == sit_1) { // if $variab is equal to the sit_1 condition ECHO... sau $val=...; } ELSEIF ($variab == sit_2) { // if $variab is equal to the sit_2 condition ECHO... sau $val=...; } ELSE { // if $variab does not meet the previous conditions ECHO... sau $val=...; } |
SWITCH with AND or OR clause
1 2 3 4 5 6 7 8 |
$variab = 1; SWITCH (TRUE) { CASE ($variab == 1 || $variab == 2): ECHO... sau $val=...; BREAK; } ECHO $val; // if we used the second option for the result (not ECHO) |
Of course, if it is necessary to meet two cumulative conditions (AND), $var > 10 && $var <= 20
will be set. For the switch with the alternative fulfillment of the condition (OR), the example below can also be used.
1 2 3 4 5 6 7 8 |
SWITCH($variab) { CASE 1: CASE 2: ECHO... sau $val=...; BREAK; } ECHO $val; // if we used the second option for the result (not ECHO) |