Home /PHP/Switch Statement

Switch Statement

The PHP switch statement is pretty much a simplified way to write multiple if statements for one variable. As you use them, you will begin to realize why they are much more convenient than writing a whole lot of if or elseif statements. If statements check one conditional, but switch statements can check for many different cases. The simple syntax of switch statements provides more readable code compared to using a lot of else if statements.

Example

$x = 3;
switch($x)
{
    case 1: //this statement is the same as if($x == 1)
        echo 'Case 1 was executed.';
    break;
    case 2: //this statement is the same as if($x == 2)
        echo 'Case 2 was executed.';
    break;
    case 3: //this statement is the same as if($x == 3)
        echo 'Case 3 was executed.';
    break;
    case 4: //this statement is the same as if($x == 4)
        echo 'Case 4 was executed.';
    break;
    default: //this statement is the same as if $x does not equal the other conditions
        echo 'Default was executed.';
    break;
}

Result

Case 3 was executed.

The syntax is slightly different from an if statement. The entire switch is implicitly using the == operator that we saw in the if statements earlier. However, we can see that we do not have to repeat that comparison operator over and over. Instead, the case is followed by the conditional variable. After the case 1, we see a :. After that colon, we have our statements to be executed.

Finally, we come to the break, which signals the end of the if-like statement. If we didn’t use break, PHP would continue to execute the other conditions in the switch statement. So, use break at the end of your case block to break out of the switch statement unless you want the following cases to be executed.

As for the default:, it means that if none of the other conditions are satisfied, do the statements following the default:. The default term is comparable to the else statement.