3
        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

abinmorth
  • 527
  • 2
  • 8
  • 25
  • 1
    You need to include break sentences in each case. The execution is "falling" from the first case until the default. https://www.php.net/manual/en/control-structures.switch.php You've got a detailed explanation of what is happening in your code in the link. – RubioRic Jun 04 '21 at 07:45
  • 1
    right, rookie mistake. I normally know this.. :o – abinmorth Jun 04 '21 at 10:19

3 Answers3

8

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"
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
4

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";
        }
SierraKomodo
  • 365
  • 4
  • 12
4

For completeness:

$states = [
    'Sleeping' => 'Is Sleeping',
    'Running' => 'Is Running',
];
echo $states[$state] ?? 'Could not retrieve state';
Álvaro González
  • 142,137
  • 41
  • 261
  • 360