question regarding switch conditionals in php
I was hoping someone had a clue as to why I got the following outputs because I was expecting something else.
$x = NULL;
switch ($x) {
case "0":
echo "String";
break;
case 0:
echo "Integer";
break;
case NULL:
echo "NULL";
break;
case FALSE:
echo "Boolean";
break;
case "":
开发者_如何转开发 echo "Empty string";
break;
default:
echo "Something else";
break;
}
// outputs "Integer" was expecting "NULL"
$x=6;
switch ($x) {
case "6b":
echo "6b";
break;
case "6":
echo "6 empty";
break;
case 6:
echo "6 full";
break;
default:
echo "6 half";
break;
}
// outputs "6b" was expecting "6 empty"
The manual says:
Note that switch/case does loose comparision.
It will first check whether NULL == "0"
which is false as NULL
as a string is not "0"
.
NULL
as integer is 0
so that will match - printing Integer.
For the 6
, it will convert the cases to integers - "6b"
will become 6
which is equal.
So it's because:
NULL != "0";
NULL == 0;
"6b" == 6;
Note:
Note that switch/case does loose comparision.
http://php.net/manual/en/control-structures.switch.php
So in stead of doing a comparison like: $x === 0
you do $x == 0
The comparison done by switch/case works with type jugling.
Basically, it uses the ==
operator, and not the ===
one.
Quoting Comparison Operators :
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
These rules also apply to the switch statement.
$x is automatically converted to an integer when doing the comparison "$x = 0". You might want to use an if/else if
structure instead, and use $x === 0
to do the comparison. ===
means "strictly equal to".
精彩评论