The Case Construct
The case
construct is part of the switch
operator and allows organizing program branching depending on the value of a variable. Each case
checks if the variable value matches its condition and executes the code if a match is found.
Syntax
switch ($variable) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default:
// default code
}
Example
A simple example of using the case
construct to check a numeric value:
<?php
$num = 2;
switch ($num) {
case 1:
echo 'One';
break;
case 2:
echo 'Two';
break;
default:
echo 'Other number';
}
?>
Code execution result:
'Two'
Example
Using multiple case
for one code block:
<?php
$char = 'b';
switch ($char) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
echo 'Vowel';
break;
default:
echo 'Consonant';
}
?>
Code execution result:
'Consonant'
Example
Using case
with strings:
<?php
$day = 'Monday';
switch ($day) {
case 'Monday':
echo 'First day of week';
break;
case 'Friday':
echo 'Last working day';
break;
default:
echo 'Regular day';
}
?>
Code execution result:
'First day of week'