【问题标题】:In which case should I use != or !==?在哪种情况下我应该使用 != 或 !==?
【发布时间】:2016-03-15 21:06:28
【问题描述】:

我目前正在开发我的第一个(小型)PHP 项目,我正在逐步自学。到目前为止一切顺利,但我确实对以下代码有疑问.. 在这种情况下我应该使用哪个..

等于:

if ($word1 != $word2) {
    echo "Your words do not match, please go back and correct this.";
    die(); }

相同:

if ($word1 !== $word2) {
    echo "Your words do not match, please go back and correct this.";
    die(); }

这两个代码都运行良好,但我仍然希望详细说明何时使用哪一个,以供将来参考和学习。

谢谢!

【问题讨论】:

  • 如果您想确保两个变量的类型相同,请使用 !== 运算符
  • @MateiMihai 如果你想确保两个变量是同一类型
  • 使用 3 个字符版本,即 ===!== 等基本上检查相等或不相等,但也测试左右手边变量的类型
  • 阅读PHP type juggling 并查看文档中的type comparison table

标签: php


【解决方案1】:

您可以通过查看 PHP 手册中的 Types comparison table 来了解它们之间的区别。

主要区别在于 !== 对比较值的类型有严格的规定,而 != 是较弱的检查。

【讨论】:

    【解决方案2】:

    一个将通过另一个将不会第一个检查仅用于相等的第二个检查和 var 类型。 var $word1 是字符串 $word2 是一个整数

    if ($word1 != $word2) {
        echo "Your words do not match, please go back and correct this.";
        }
    //with this if stament will pass the test without echo out nothing.
    
    if ($word1 !== $word2) {
        echo "Your words do not match, please go back and correct this.";
         } //this one will not pass and will echo out your string 
     ?>
    

    【讨论】:

    • 错误答案。请参考this
    猜你喜欢
    • 2015-11-20
    • 2016-09-14
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2022-07-22
    相关资源
    最近更新 更多