Published: May 15, 2021 by C.S. Rhymes

In the previous article we discussed the if statement, where it said you can have many different elseif statements if you wanted to handle many different scenarios, but it gets to a point where you should consider swapping to a switch statement.

$myVar = 'green';

if ($myVar === 'red') {
    echo 'It is red';
} elseif ($myVar === 'blue') {
    echo 'It is blue';
} elseif ($myVar === 'green') {
    echo 'It is green';
}

This can be rewritten using a switch statement. Each condition you want to match has a case where you pass in the variable you want to match. Within the case, you put the code you want to run if the condition matches. Then you need to add a break, otherwise the code will continue to check for matches in the rest of the switch statement.

#php #code #beginner

The PHP Switch Statement
1.15 GEEK