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

前端 未结 11 2101
故里飘歌
故里飘歌 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:26

    Variables have a type and a value.

    • $var = "test" is a string that contain "test"
    • $var2 = 24 is an integer vhose value is 24.

    When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do

    if ($var == 1) {... do something ...}
    

    PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.

    When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.

    This is useful, for example, when you have a function that can return false (on error) and 0 (result) :

    if(myFunction() == false) { ... error on myFunction ... }
    

    This code is wrong as if myFunction() returns 0, it is casted to false and you seem to have an error. The correct code is :

    if(myFunction() === false) { ... error on myFunction ... }
    

    because the test is that the return value "is a boolean and is false" and not "can be casted to false".

提交回复
热议问题