note 34020 added to control-structures.switch
| From: | bishop at rack1 dot php dot net | Date: | Mon, 14 Jul 2003 05:26:30 +0000 |
| Subject: | note 34020 added to control-structures.switch | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-52059@lists.php.net to get a copy of this message | ||
As jason at devnetwork dot net and others have pointed out, using switch() when you wish to compare
against strings can be dangerous:
$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:
$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.
----
Manual Page -- http://www.php.net/manual/en/control-structures.switch.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34020
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34020&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34020&report=yes