What does === do in PHP

后端 未结 8 1589
天涯浪人
天涯浪人 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-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.

提交回复
热议问题