note 59991 deleted from control-structures.switch by cmb
| From: | cmb@php.net | Date: | Sun, 21 Apr 2019 11:48:49 +0000 |
| Subject: | note 59991 deleted from control-structures.switch by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210638@lists.php.net to get a copy of this message | ||
Note Submitter: scott at firefallpro dot com
----
It's has already been mentioned indirectly in a few posts, but it is important to realize that
switch statements evaluate each case with the "==" operator by default. This can lead to
unexpected results when comparing strings to integers, because PHP will convert the string to an
integer. In many cases this means a string can be equivalent to the integer 0.
Example:
<?php
$x = 0;
switch($x) {
case "a":
echo "a";
break;
case "b":
echo "b";
break;
default
echo "default";
}
?>
The result will be an "a" echoed out. What PHP does in this instance, is once it realizes
that it's attempting to compare string ("a") to an integer (0), it converts
"a" into an integer which ends up satisfying the first case.
The rules for string conversion into integers is available at:
http://us3.php.net/manual/en/language.types.string.php
The easiest way to combat this issue is to force type comparison by using the "==="
operator. This makes PHP forego the string to integer conversion.
Example:
<?php
switch(true) {
case $x === "a":
echo "a";
break;
case $x === "b":
echo "b";
break;
default
echo "default";
}
?>
Or the switch input can be type-casted to always be a string, etc.
Also note that even though a conditional statement needs to be explicitly set in each case to gain
expected behavior, the switch can still execute faster then an "ifelse" block because PHP
will not continue to evaluate conditions once a case has been satisfied.