如何在PHP中使用带整数0的开关?

问题描述 投票:1回答:3

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

如何更改此设置,以便交换机按预期写入“零”?

php comparison-operators
3个回答
4
投票

switch / case语句使用松散比较,不管你喜欢与否,0 == "anything"都是true

Comparison Operators

[...]如果您将数字与字符串进行比较或比较涉及数字字符串,则每个字符串将转换为数字,并以数字方式执行比较。这些规则也适用于switch语句。 [...]

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

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

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

1
投票

开关/案例陈述使用“松散比较”(即==。在这种情况下,0也意味着false1也意味着true。(http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose

为避免此问题,有两种解决方案:

1)根据@zzlalani的建议,添加引号。

   case '0': ...

2)显式转换switch语句强制进行严格比较(===

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

0
投票

这样做

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

编辑:

如何更改此设置,以便交换机按预期写入“零”?

您需要移动上面的案例陈述。

$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没有进行“严格类型”检查。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.