PHP:切换奇怪的行为

时间:2013-01-31 01:41:09

标签: php logic

  

可能重复:
  PHP expresses two different strings to be the same

我在解决切换案例指令中导致这种奇怪行为的原因时遇到了问题。

代码是这样的:

<?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;
}
?>

此指令的结果应为这是G

嗯,不是这样。始终返回 The F Word

如果我们将开头的 0E9 左指令撤消,并尝试找到值 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;
}
?>

现在返回这是G

0E2 0E9 值不会被解释为文字?这些价值观是保留的吗?

有人可以解释这种行为吗?

2 个答案:

答案 0 :(得分:5)

"0E2" == "0E9"true,因为它们是数字字符串

注意:切换使用松散比较

请检查此问题:PHP expresses two different strings to be the same

答案 1 :(得分:1)

这些数字字符串彼此相等。总是如此。不幸的是,没有办法通过switch强制进行等价比较。您只需使用if

if ($myKey === '0E9') {
   echo 'g';
}
else if ($myKey === '0E2') {
   echo 'f';
}
else {
   echo "Nothing here";
}

我想你也可以削减前导零点。