3

Possible Duplicate:
PHP expresses two different strings to be the same

I have a problem understanding what's causes this weird behavior in a switch case instruction.

The code is 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 instruction should be This is the G

Well, not so. always returns The F Word

If we reverse the 0E9 left instructions for the beginning 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 returns always This is the G

0E2 and 0E9 values ​​are not interpreted as text? Those Values ​​are reserved?

Someone can explain this behavior?

Community
  • 1
  • 1
manuerumx
  • 1,230
  • 14
  • 28

2 Answers2

5

"0E2" == "0E9" is true because they are numerical strings.

Note: switch use loose comparision.

Check this question: PHP expresses two different strings to be the same.

Community
  • 1
  • 1
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Numeric strings such as these are equal to each other .. always. Unfortunately, there is no way to force an equivalence comparison via switch. You just have 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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405