Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php why does TRUE == "expired"?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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' ???

>Solution :

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 ===

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading