如何在PHP中使用整数0来使用switch语句?

5

将整数0作为开关参数将获取第一个结果"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;

我该如何更改这个开关,以便它按预期输出“zero”?
3个回答

7

switch/case语句使用宽松比较,不管你喜不喜欢,0 == "anything"都是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

一种解决方案是将所有的case语句替换为字符串,并进行字符串比较:

$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语句使用“宽松比较”(即==)。在这种情况下,0也表示false1也表示true。(参考http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose
为了避免这个问题,有两个解决方案:
1)如@zzlalani所建议的,添加引号。
请按照格式要求返回结果。
   case '0': ...

2) 显式地将switch语句强制转换为严格比较(===)。

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

1
像这样做
$data=0;
switch ($data)
{
    case 0:
        echo "bar";
        break;
    default: 
        echo "foo";
    break;
}

编辑:

我该如何更改此处,以便开关按预期写入“zero”?

您需要将case语句移动到上面。

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

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

这是因为switch不进行“严格类型”检查。

3
笑!问题不仅仅是写“酒吧”这么简单。 - rubo77
你为什么改变了你的问题?那么这个答案就无效了吗? - Shankar Narayana Damodaran
我没有改变它,我只是澄清了整数0的问题(请参见标题)。 - rubo77
1
如果 $data 改变成任何值 $data='anything';,那会怎么样? - zzlalani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接