Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Switch weird behavior [duplicate]

Tags:

php

logic

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?

like image 207
manuerumx Avatar asked Dec 01 '25 03:12

manuerumx


1 Answers

"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.

like image 86
xdazz Avatar answered Dec 02 '25 16:12

xdazz