echo $state; //debug
switch($state){
case "Sleeping":
$label = "Is Sleeping";
case "Running":
$label = "Is Running";
default:
$label = "Could not retrieve state";
}
$state is filled from an SQL database (Enum type), the echo message prints "Sleeping", but the $label is filled with the default value
PHP switch statements continue executing the remainder of the switch block after finding a match, until it finds a break;
statement. You'll want to add break;
to the end of each case:
echo $state; //debug
switch($state){
case "Sleeping":
$label = "Is Sleeping";
break;
case "Running":
$label = "Is Running";
break;
default:
$label = "Could not retrieve state";
}
In your case choose match
( PHP 8 ) expression is significantly shorter and it doesn't require a break
statement.
$state = "Running";
$label = match ($state) {
"Sleeping"=> "Is Sleeping",
"Running" => "Is Running",
default => "Could not retrieve state"
};
echo $label; // "Is Running"
For completeness:
$states = [
'Sleeping' => 'Is Sleeping',
'Running' => 'Is Running',
];
echo $states[$state] ?? 'Could not retrieve state';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.