This drove me nuts for a few hours.
I have a function returning one of the three following values:
function checkValid() {
...
return array("expired",$oldDate,$newDate) ;
return array(true,$oldDate,$newDate) ;
return array(false,$oldDate,$newDate) ;
}
list($isValid,$oDate,$nDate) = checkValid() ;
if ($isValid == "expired") {
...
...do blah
}
...and everytime the condition returned true
, the if ($isValid == "expired") { ... }
would trigger. So I ran some tests and sure enough:
$isValid = true ;
if ($isValid == "expired") {
echo "Yup...some how 'expired' equals TRUE" ;
} else {
echo "Nope....it doesn't equal true" ;
}
output: Yup...some how 'expired' equals TRUE
When I changed the if/condition to:
$isValid = true ;
if ($isValid === "expired") {
echo "Yup...some how 'expired' equals TRUE" ;
} else {
echo "Nope....it doesn't equal true" ;
}
output: Nope....it doesn't equal true
I am baffled by this. Why would true == 'expired'
or 1 == 'expired'
???
CodePudding user response:
When using two equal signs ==
php does type coersion under the hood and checks for truthy cases which includes all numbers other than 0
, boolean true
, all string other than empty strings and some other cases.
If you want to check for an exact match, you should use three equal signs ===