PHP 的布尔比较处理 - 解释?

发布于 2024-12-13 07:54:32 字数 198 浏览 5 评论 0 原文

我遇到了一些让我感兴趣的事情,我只是想知道如何解释为什么会发生这种情况。

$var = true;
if($var == 'X'){
  echo 'pass';
}

上面的代码会触发“pass”...为什么?如果我使用 $var === 'x' 它会按预期运行。

谢谢。

I've come across something that intrigued me and I just want to know how to explain why it's happening.

$var = true;
if($var == 'X'){
  echo 'pass';
}

The above code will trigger 'pass'... why? If i use $var === 'x' it'll behave as expected.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独孤求败 2024-12-20 07:54:32

非空字符串将始终评估为 TRUE 请参阅 PHP 的关于布尔计算的文档。正如您所发现的,您必须使用 === 进行严格类型比较,以测试字符串 'X' 是否与布尔值 TRUE 相同。

'X' == TRUE  // TRUE
'' == TRUE   // FALSE
'X' === TRUE // FALSE

A non-empty string will always evaluate to TRUE See PHP's documentation on boolean evaluation. As you have discovered, you must use === for strict type comparison to test whether the string 'X' is identical to the boolean TRUE.

'X' == TRUE  // TRUE
'' == TRUE   // FALSE
'X' === TRUE // FALSE
烂人 2024-12-20 07:54:32

PHP 的类型杂耍可能有其优点,但在我看来,它会导致“危险”的误解。其他不直观的例子是:

'abc' == 0;
0 == null;
'' == null;
1 == '1y?z'

由于各种原因,这些在 PHP 中都被认为是正确的。我总是建议编写您自己的函数来检查相等性,它会按照您的预期工作(或者您是否拥有整个 PHP 在你的脑海中输入比较矩阵?);

PHP's type juggling may have it's advantages, but in my opinion it leads to "dangerous" misunderstandings. Other examples that are not intuitiv would be:

'abc' == 0;
0 == null;
'' == null;
1 == '1y?z'

These are all considered true in PHP for various reasons. I always recommend to write your own function to check for equality, which works as you expect it (or do you have the whole PHP type comparison matrix in your mind?);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文