The == is a comparison operator, checking for the equality of two values. $a==$b is TRUE if $a is equal to $b. The === also compares two values but in addition to values, it also compares their types (data types). === is called identical operator.
See the example below
<?
if(0==false){
// this is true
}
?>
as 0 is considered when used in loops and if conditions, so the above condition will evaluate to TRUE, while the code below evaluates to TRUE
<?
if(0===false){
// this is false
}
?>
this time === i.e identical operator is used which compares the two values and their datatypes, 0 is an integer while false is a boolean. This time it evaluates to false.
Where to use === and !==
strpos() function is used to find the occurance of one string within another. If found, it returns the index and returns -1 otherwise. Consider the example below
<?
$a="This is our main string";
$b="main";
$x=strpos($a,$b);
echo $x; // prints 12
if($x){ // works fine here
echo "Match found!";
}
else{
echo "Match not found!";
}
?>
Now look at the code below
<?
$a="This is our main string";
$b="This";
$x=strpos($a,$b); //found at index 0
if($x){ // doesn't work, as it evaluates to false
echo "Match found!";
}
else{
echo "Match not found!";
}
?>
This time the output will be "Match not found!" which is wrong. === operator is used in situations like this. So the correct implementation will be
<?
$a="This is our main string";
$b="This";
$x=strpos($a,$b); //found at index 0
if($x!==false){ // match values and their types as well
echo "Match found!";
}
else{
echo "Match not found!";
}
?>