How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

前端 未结 11 2103
故里飘歌
故里飘歌 2020-11-22 16:52

What is the difference between == and === in PHP?

What would be some useful examples?


Additionally, how are these operators us

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:30

    It's all about data types. Take a BOOL (true or false) for example:

    true also equals 1 and false also equals 0

    The == does not care about the data types when comparing: So if you had a variable that is 1 (which could also be true):

    $var=1;

    And then compare with the ==:

    if ($var == true)
    {
        echo"var is true";
    }
    

    But $var does not actually equal true, does it? It has the int value of 1 instead, which in turn, is equal to true.

    With ===, the data types are checked to make sure the two variables/objects/whatever are using the same type.

    So if I did

    if ($var === true)
    {
        echo "var is true";
    }
    

    that condition would not be true, as $var !== true it only == true (if you know what I mean).

    Why would you need this?

    Simple - let's take a look at one of PHP's functions: array_search():

    The array_search() function simply searches for a value in an array, and returns the key of the element the value was found in. If the value could not be found in the array, it returns false. But, what if you did an array_search() on a value that was stored in the first element of the array (which would have the array key of 0)....the array_search() function would return 0...which is equal to false..

    So if you did:

    $arr = array("name");
    if (array_search("name", $arr) == false)
    {
        // This would return 0 (the key of the element the val was found
        // in), but because we're using ==, we'll think the function
        // actually returned false...when it didn't.
    }
    

    So, do you see how this could be an issue now?

    Most people don't use == false when checking if a function returns false. Instead, they use the !. But actually, this is exactly the same as using ==false, so if you did:

    $arr = array("name");
    if (!array_search("name", $arr)) // This is the same as doing (array_search("name", $arr) == false)
    

    So for things like that, you would use the === instead, so that the data type is checked.

提交回复
热议问题