PHP: toggle strange behavior
Possible duplicate:
PHP expresses two different strings the same
I have a problem understanding what is causing this strange behavior in a case switch statement.
The code looks like this:
<?php
$myKey = "0E9";
switch ($myKey) {
case "0E2":
echo "The F Word";
break;
case "0E9":
echo "This is the G";
break;
default:
echo "Nothing here";
break;
}
?>
The result of this command should be This G
Well, not like that. always returns Word F
If we reverse the left instructions 0E9 to begin with and try to find the value 0E2
<?php
$myKey = "0E2";
switch ($myKey) {
case "0E9":
echo "The G String";
break;
case "0E2":
echo "The F Word";
break;
default:
echo "Nothing here";
break;
}
?>
Now it always comes back It's G
The values0E2 and 0E9 are not interpreted as text? Are these values reserved?
Can anyone explain this behavior?
source to share
"0E2" == "0E9"
true
because they are numeric strings .
Note. the switch uses free comparison .
Check this question: PHP expresses two different strings as the same .
source to share
Numeric strings like these are equal to each other .. always. Unfortunately, there is no way to force an equivalence comparison via switch
. You just need to use if
:
if ($myKey === '0E9') {
echo 'g';
}
else if ($myKey === '0E2') {
echo 'f';
}
else {
echo "Nothing here";
}
You could also trim the leading zero, I suppose.
source to share