Why Not “Switch” from If/Else?
Are you tired of writing if/elseif/elseif/…/else statements? You’re not alone. There is a more elegant way to write such large statements: the PHP switch statement.
Let’s take a look at the anatomy of the switch statement.
switch ( $arg ) {
case "value_1":
expression if matched value_1
break; // terminate
case "value_2":
expression if matched value_2
break; // terminate
...
default:
execute if no cases matched
}
The switch statement accepts an argument. It has a series of “cases” that could potentially match the value of the argument. If it matches, the statements inside of that particular case are executed. If a break statement is included, the termination ends, otherwise the statements continue to execute until PHP either reaches the end of the switch statement or a break statement is encountered.
Switch statements can be converted into if/elseif/else statement, and vice versa (for the most part). Let’s take a look at an example starting with the if/elseif/else statement. We’ll be converting that statement into a switch statement.
<?php
$name = "Dino";
if ( $name == "Dino" ) {
echo "Hey man!";
} elseif ( $name == "Harrison" ) {
echo "How's it going?";
} elseif ( $name == "Amy" ) {
echo "Hello";
} else {
echo "Hi";
}
?>
The if/elseif/else statement above looks at the $name variable. Depending on which condition matches, a specific greeting is displayed. If the $name variable contains the value “Harrison,” PHP will output “How’s it going?” If no matches are found, PHP will output “Hi.” Let’s convert this into a switch statement.
<?php
$name = "Dino";
switch ( $name ) {
case "Dino":
echo "Hey man";
break;
case "Harrison":
echo "How's it going?";
break;
case "Amy":
echo "Hello";
break;
default:
echo "Hi";
}
?>
As you can see, the code is a lot more cleaner to look at than the if/elseif/else statement. In the example above, PHP will output “Hey man” since “Dino” will be matched. It will not continue execution due to the break statement. If there were several dozen options, you could see how a switch statement could be beneficial. We can even make it more compact; we don’t have to place each statement on a new line.
<?php
$name = "Dino";
switch ( $name ) {
case "Dino": echo "Hey man"; break;
case "Harrison": echo "How's it going?"; break;
case "Amy": echo "Hello"; break;
default: echo "Hi";
}
?>
The code is easy to read: clarity is key.
We can have pretty much any expression that we want. Let’s use the switch statement to assign a value to a variable depending on a specific condition.
<?php
$money_in_the_bank = 40000;
$car = "";
switch( $money_in_the_bank ) {
case 1000000: $car = "McLaren F1"; break;
case 500000: $car = "Murcielago"; break;
case 100000: $car = "Porsche 911"; break;
case 75000: $car = "Hellcat"; break;
case 40000: $car = "Subaru STi"; break;
case 25000: $car = "Civic"; break;
}
var_dump( $car );
?>
In this example, PHP:
- Accepts the $money_in_the_bank argument.
- It looks at the first case and sees that 40000 does not match 1000000. It skips that condition.
- It looks at the second case and sees that 40000 does not match 500000. It skips that condition.
- It looks at the third case and sees that 40000 does not match 100000. It skips that condition.
- It looks at the fourth case and sees that 40000 does not match 75000. It skips that condition.
- It looks at the fifth case and sees that 40000 does match 40000.
- PHP executes the statements inside of the case body. The value “Subaru STi” is assigned to the $car variable.
- The break statement is encountered. PHP exits the switch statement.
- PHP encounters the var_dump function and dumps the contents of the $car variable onto the screen, which in this case contains the value “Subaru STi.”
What if the break statements were not there? PHP would continue executing the code until it either reached the end of the switch statement or another break statement was encountered.
<?php
$money_in_the_bank2 = 1000000;
switch( $money_in_the_bank2 ) {
case 1000000: $car = "McLaren F1";
case 500000: $car = "Murcielago";
case 100000: $car = "Porsche 911";
case 75000: $car = "Hellcat";
case 40000: $car = "Subaru STi";
case 25000: $car = "Civic";
}
var_dump($car);
?>
In this example, PHP matches the value in the first case. However, because there is no break statement, PHP keeps going. It assigns the value “Murcielago” to the $car variable next. Still no break statement. It keeps going until it reaches the closing curly brace. By that time, it assigned McLaren F1, Murcielago, Porsche 911, Hellcat, Subaru STi, and finally Civic to the $car variable. When we call the var_dump function, it outputs “Civic.” You can see with this simple example what a costly mistake this could be. You just spent a million dollars on a Civic.
There are times when we want to selectively use the break statement.
<?php
$brand = "Chevy";
switch( $brand ) {
case "Apple":
case "HP":
case "Samsung":
echo "This is a tech company";
break;
case "Audi":
case "Chevy":
case "Porsche":
case "Subaru":
echo "This is a car company";
break;
default:
echo "I don't know what this is.";
}
?>
In this code, we don’t want to keep writing “This is a tech company” or “This is a car company” over and over again. It doesn’t matter if it’s Chevy or Subaru, it’s a car company. What will PHP do in this example?
- PHP enters the switch statement and tries to match the value stored in the $brand variable with one of the cases.
- It goes down until it reaches the Chevy case.
- PHP goes to execute the statement inside of the Chevy case. There is nothing there. There’s no break statement either. So, PHP keeps going.
- It goes down to the next statement which echoes out “This is a car company.” The statement is executed.
- PHP encounters the break statement and exits the switch statement.
We can do other types of comparison operators inside of the case statements. Imagine that we wanted to tell the student what grade he or she received on his or her test. We would either have to create a case for each value between 0 and 100, or we could use the comparison operators.
<?php
$grade = 80;
// A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59
switch( $grade ) {
case ($grade >= 90): echo "A"; break;
case ($grade >= 80): echo "B"; break;
case ($grade >= 70): echo "C"; break;
case ($grade >= 60): echo "D"; break;
default: echo "F";
}
?>
The order is important. We start with the highest grade and work our way down. PHP will output “B.” If the code was reversed, PHP would output “D” since $grade ≥ 60 is a true statement.
PHP Tutorial Series
Continue your learning with these articles
tired of if/else? How about ternary?
The ternary operator is a way to quickly express if/else statements. If the boolean expression evaluates to true, the “if_true” result is displayed, otherwise the “if_false” result is displayed.
Why Not “Switch” from If/Else?
Are you tired of writing if/elseif/elseif/…/else statements? You’re not alone. There is a more elegant way to write such large statements: the switch statement.
THIS MIGHT TAKE A WHILE
The while loop says, “while the expression is true, do something inside of the loop body.” If we passed the value “true” to the conditional expression, the loop would run forever (well, as long as PHP allows it to run before it crashes).