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
It will check if the datatype is the same as well as the value
if ("21" == 21) // true
if ("21" === 21) // false
===
compares value and type.
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.
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...)
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.
== doesn't compare types, === does.
0 == false
evaluates to true but
0 === false
does not