Search code examples
phpcomparison-operators

How to use switch with integer 0 in PHP?


having the integer 0 as switch parameter will take the first result "foo":

$data=0; // $data is usually coming from somewhere else, set to 0 here to show the problem
switch ($data) :
    case "anything":
        echo "foo";
        break;
    case 0:
        echo "zero";
        break;
    default: 
        echo "bar";
endswitch;

How do I change this, so the switch will write "zero" as expected?


Solution

  • The switch/case statement uses loose comparison, and, like it or not, 0 == "anything" is true:

    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. [...]

    var_dump(0 == "a"); // 0 == 0 -> true
    

    One solution is to change all case statements to string, and do a string comparison:

    $data = 0;
    switch ((string) $data): ## <- changed this
        case "anything":
            echo "foo";
            break;
        case "0":            ## <- and this
            echo "zero";
            break;
        default: 
            echo "bar";
    endswitch;