gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:44:26 25 4
gpt4 key购买 nike

将整数 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;

如何更改此设置,以便开关按预期写入“零”?

最佳答案

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;

关于php - 如何在 PHP 中使用带有整数 0 的开关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19901340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com