Not equal to != and !== in PHP

前端 未结 4 1797
南旧
南旧 2020-11-27 12:46

I\'ve always done this: if ($foo !== $bar)

But I realized that if ($foo != $bar) is correct too.

Double = still works

相关标签:
4条回答
  • 2020-11-27 13:26

    You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php

    It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

    0 讨论(0)
  • 2020-11-27 13:41

    == and != do not take into account the data type of the variables you compare. So these would all return true:

    '0'   == 0
    false == 0
    NULL  == false
    

    === and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:

    '0'   === 0
    false === 0
    NULL  === false
    

    You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():

    // This returns 0 because F exists as the first character, but as my above example,
    // 0 could mean false, so using == or != would return an incorrect result
    var_dump(strpos('Foo', 'F') != false);  // bool(false)
    var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
    
    0 讨论(0)
  • 2020-11-27 13:43

    !== should match the value and data type

    != just match the value ignoring the data type

    $num = '1';
    $num2 = 1;
    
    $num == $num2; // returns true    
    $num === $num2; // returns false because $num is a string and $num2 is an integer
    
    0 讨论(0)
  • 2020-11-27 13:46

    $a !== $b TRUE if $a is not equal to $b, or they are not of the same type

    Please Refer to http://php.net/manual/en/language.operators.comparison.php

    0 讨论(0)
提交回复
热议问题