What does === do in PHP

后端 未结 8 1585
天涯浪人
天涯浪人 2021-01-05 23:25

I have been programming in PHP for a while but I still dont understand the difference between == and ===. I know that = is assignment. And == is equals to. So what is the pu

相关标签:
8条回答
  • 2021-01-05 23:58

    It will check if the datatype is the same as well as the value

    if ("21" == 21) // true
    if ("21" === 21) // false
    
    0 讨论(0)
  • 2021-01-05 23:58

    === compares value and type.

    0 讨论(0)
  • 2021-01-05 23:59

    The PHP manual has a couple of very nice tables ("Loose comparisons with ==" and "Strict comparisons with ===") that show what result == and === will give when comparing various variable types.

    0 讨论(0)
  • 2021-01-06 00:06

    Minimally, === is faster than == because theres no automagic casting/coersion going on, but its so minimal its hardly worth mentioning. (of course, I just mentioned it...)

    0 讨论(0)
  • 2021-01-06 00:11

    It compares both value and type equality.

     if("45" === 45) //false
     if(45 === 45) //true
     if(0 === false)//false
    

    It has an analog: !== which compares type and value inequality

     if("45" !== 45) //true
     if(45 !== 45) //false
     if(0 !== false)//true
    

    It's especially useful for functions like strpos - which can return 0 validly.

     strpos("hello world", "hello") //0 is the position of "hello"
    
     //now you try and test if "hello" is in the string...
    
     if(strpos("hello world", "hello")) 
     //evaluates to false, even though hello is in the string
    
     if(strpos("hello world", "hello") !== false) 
     //correctly evaluates to true: 0 is not value- and type-equal to false
    

    Here's a good wikipedia table listing other languages that have an analogy to triple-equals.

    0 讨论(0)
  • 2021-01-06 00:11

    == doesn't compare types, === does.

    0 == false
    

    evaluates to true but

    0 === false
    

    does not

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