How Truth Tables Ruined My Afternoon

This piece of code was killing me this afternoon:

$DB_ERROR = -1;
$API_ERROR = -2;
$UI_ERROR = -3;

$errorCodes = array($DB_ERROR, $API_ERROR, $UI_ERROR);

$returnCode = TRUE;
$isError = in_array($returnCode, $errorCodes);
print($isError);

I was expecting $isError to be FALSE but it kept turning up as TRUE. I just couldn’t understand it. That is until I read the online docs:

When converting to boolean, the following values are considered FALSE:

* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string “0″
* an array with zero elements
* an object with zero member variables (PHP 4 only)
* the special type NULL (including unset variables)
* SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Do you see what I was assuming here? I considered TRUE to be a 1 and FALSE to be everything but a 1. I guess I’m just so used to those truth tables with 1 representing true (thank you very much Discrete Mathematics For Computer Science). But hey you’ve gotta work with whatever the language gives you.

At first I thought about converting $returnCode to an integer before I make that in_array comparison but then after reading more of the online docs I found something cleaner:

$isError = in_array($returnCode, $errorCodes, TRUE);

That extra TRUE checks the types as well as the values.

Comments

Leave a Reply