Switch-Case Construct in PHP
PHP has a special switch-case construct,
which is used to select one value
from a range of values. Study its syntax:
<?php
switch (variable) {
case 'variant 1':
/*
code that will execute if
the variable has value1
*/
break;
case 'variant 2':
/*
code that will execute if
the variable has value2
*/
break;
case 'variant 3':
/*
code that will execute if
the variable has value3
*/
break;
default:
/*
code that will execute if
it doesn't match any value
*/
break;
}
?>
As you can see, switch-case
is an alternative to multiple
elseif statements. Let's look at an example.
Suppose we have the following code:
<?php
$num = 1;
if ($num === 1) {
echo 'variant 1';
} elseif ($num === 2) {
echo 'variant 2';
} elseif ($num === 3) {
echo 'variant 3';
} else {
echo 'variant not supported';
}
?>
Let's rewrite this code using the switch-case construct:
<?php
$num = 1;
switch ($num) {
case 1:
echo 'variant 1';
break;
case 2:
echo 'variant 2';
break;
case 3:
echo 'variant 3';
break;
default:
echo 'variant not supported';
break;
}
?>
The variable $num can take values
1, 2, 3 or 4.
Determine which season the value
of this variable falls into.