note 34020 deleted from control-structures.switch by cmb
| From: | cmb@php.net | Date: | Sun, 21 Apr 2019 11:49:31 +0000 |
| Subject: | note 34020 deleted from control-structures.switch by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210639@lists.php.net to get a copy of this message | ||
Note Submitter: bishop
----
As jason at devnetwork dot net and others have pointed out, using switch() when you wish to compare
against strings can be dangerous:
<?php
$bug = 0;
switch ($bug) {
case 'fly':
echo 'flies buzz';
break;
case 'mantis':
echo 'mantes pray';
break;
default:
echo 'swat, splat, you are dead';
break;
}
?>
Will print "flies buzz", NOT "swat, splat, you are dead".
Remember PHP says that 'fly' == 0, or in general string == 0 is true.
Anyway, avoid that with:
<?php
$bug = 0;
switch ($bug === 0 ? '' : $bug) {
case 'fly':
echo 'flies buzz';
break;
case 'mantis':
echo 'mantes pray';
break;
default:
echo 'swat, splat, you are dead';
break;
}
?>
Prints out what you expect:
Swat
Splat
You are dead
P.S.: that's an empty string (single quote single quote), not a spurious double quote.