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 purpose of ===?
It will check if the datatype is the same as well as the value
if ("21" == 21) // true
if ("21" === 21) // false
== doesn't compare types, === does.
0 == false
evaluates to true but
0 === false
does not
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.
It's a true equality comparison.
"" == False
for instance is true
.
"" === False
is false
It is true that === compares both value and type, but there is one case which hasn't been mentioned yet and that is when you compare objects with == and ===.
Given the following code:
class TestClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
$a = new TestClass("a");
$b = new TestClass("a");
var_dump($a == $b); // true
var_dump($a === $b); // false
In case of objects === compares reference, not type and value (as $a and $b are of both equal type and value).
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...)