Branching with the switch Statement - Images: Japanese
Hey there, everyone. Hope you're doing well!
Next up, let's take a look at the 'switch statement'. It's similar to an if statement in that it handles branching logic — but while an if statement branches into two paths at a time, a switch statement lets you handle many branches all at once.
The switch statement is available in almost every language besides PHP, and it sees moderate use overall. That said, PHP's switch statement has some quirks that make it a bit awkward to work with, so even when you need multiple branches, it's common to just use if statements instead. We'll look at that side of things too.
Here's the basic syntax:
<?php
$num = 1;
switch($num){
case 1:
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
The syntax is a bit involved, so let's go through it piece by piece.
First, the variable $num is assigned the value 1. Then we have the keyword switch — this plays the same role as if in an if statement.
Next come the parentheses (). You put the variable you want to evaluate inside them — in this case, $num.
Then comes the {} block, inside which you write case, followed by a space, a value, and then a ':'. This means: "if the variable in the parentheses equals this value, run the code after the colon." So in this example, when $num is 1, var_dump('It\'s 1!'); and break; are executed.
case 2 works the same way — if $num equals 2, the code after the colon runs. The default at the end is what runs when none of the preceding case conditions match.
Let's try an example:
<?php
$num = 4;
switch($num){
case 1:
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
We've changed $num to 4. None of the case values match 4, so the default block — var_dump('It\'s the default!'); and break; — should run. Here's the output:
string(18) "It's the default!"
The default block ran as expected.
Now, about that break that keeps showing up — this is called a break statement, and it means "exit the block." In a switch statement, if you leave out a break, PHP will continue executing all the code that follows the matching case, not just that one block. Let's see what that looks like:
<?php
$num = 1;
switch($num){
case 1:
var_dump('It\'s 1!');
case 2:
var_dump('It\'s 2!');
case 3:
var_dump('It\'s 3!');
default:
var_dump('It\'s the default!');
break;
}
We've removed most of the break statements. $num is 1. Here's what happens when you run it:
string(7) "It's 1!" string(7) "It's 2!" string(7) "It's 3!" string(18) "It's the default!"
Everything from case 1: onward got executed. That's the behavior you get when you omit break. This pattern is quite rare in practice, so it's fine to just memorize: "always write break with every case in a switch statement."
Now for a slightly more advanced use. You can also use strings as the comparison value:
<?php
$num = 'miku';
switch($num){
case 'miku':
var_dump('It\'s miku!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
$num holds the string 'miku'. Since case 'miku': is listed, the code after it — var_dump('It\'s miku!'); and break; — should run. And sure enough:
string(10) "It's miku!"
Works perfectly. That's the basic way to use a switch statement. Feeling good so far?
Now let's get into the part where PHP's switch statement starts to show its rough edges. PHP's switch statement does not use strict comparison. It uses ==, not === — meaning it does not check whether the types match. Because of this, the following code will execute the case 1: block:
<?php
$num = '1';
switch($num){
case 1: // Not a strict comparison, so this case matches.
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
$num holds the string '1' — not the integer 1. But because the comparison isn't strict, the string '1' and the integer 1 are considered equal, and case 1: fires.
Let's push it further with a genuinely odd case. Here we pass the boolean false through a switch statement:
<?php
$num = false;
switch($num){
case 0:
var_dump('It\'s 0!');
break;
case 1:
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
Running this gives:
string(7) "It's 0!"
You might expect default to run, but case 0: fires instead. That's because false and 0 are considered equal under non-strict comparison.
Most other languages use strict comparison in switch statements, but PHP is different. PHP's switch statement is genuinely tricky in this way.
One workaround is to write it like this:
<?php
$num = 1;
switch(true){
case $num === 0:
var_dump('It\'s 0!');
break;
case $num === 1:
var_dump('It\'s 1!');
break;
case $num === 2:
var_dump('It\'s 2!');
break;
default:
var_dump('It\'s the default!');
break;
}
In PHP you can write expressions after case. By using === strict comparison in each case expression, and putting the boolean true inside the switch's parentheses, you effectively get a switch statement that performs strict comparisons.
This works — but at that point, it's hard not to think "why not just use an if statement?"
<?php
$num = 1;
if($num === 0) // The switch above can be rewritten like this.
var_dump('It\'s 0!');
else if($num === 1)
var_dump('It\'s 1!');
else if($num === 2)
var_dump('It\'s 2!');
else
var_dump('It\'s the default!');
So switch statements don't see heavy use in PHP — in practice, if statements tend to be the go-to choice.
And that wraps this one up! In the next article, we'll write a program that displays the current time when the page is accessed. That'll give you a chance to see switch statements, if statements, and comparison operators in action. See you there!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.