How to use switch with integer 0 in PHP?

强颜欢笑 提交于 2020-01-21 19:09:18

问题


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?


回答1:


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;



回答2:


Switch/case statement uses "loose-comparison" (i.e. ==. in this case, 0 also means false and 1 also means true. (http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose)

To avoid this problem, two solutions:

1) As suggested by @zzlalani, add quotes.

   case '0': ...

2) Explicitly cast the switch statement to force a strict comparison (===)

    switch((string)($data)) { ... }



回答3:


Do like this

$data=0;
switch ($data)
{
    case 0:
        echo "bar";
        break;
    default: 
        echo "foo";
    break;
}

EDIT :

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

You need to move your case statement above.

$data=0;
switch ($data) :
    case 0:            // Moved this case to the begining
        echo "zero";
        break;

    case "anything":
        echo "foo";
        break;
    default: 
        echo "bar";
endswitch;

This is because switch does not do a "strict-type" checking.



来源:https://stackoverflow.com/questions/19901340/how-to-use-switch-with-integer-0-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!