Parsing a string into a boolean value in PHP

Today I was playing with PHP, and I discovered that the string values "true" and "false" are not correctly parsed to boolean in a condition, for example considering the following function:

function isBoolean($value) {
   if ($value) {
      return true;
   } else {
      return false;
   }
}

If I execute:

isBoolean("true") // Returns true
isBoolean("") // Returns false
isBoolean("false") // Returns true, instead of false
isBoolean("asd") // Returns true, instead of false

It only seems to work with "1" and "0" values:

isBoolean("1") // Returns true
isBoolean("0") // Returns false

Is there a native function in PHP to parse "true" and "false" strings into boolean?


Solution 1:

There is a native PHP method of doing this which uses PHP's filter_var method:

$bool = filter_var($value, FILTER_VALIDATE_BOOLEAN);

According to PHP's manual:

Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.

If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

Solution 2:

The reason is that all strings evaluate to true when converting them to boolean, except "0" and "" (empty string).

The following function will do exactly what you want: it behaves exactly like PHP, but will also evaluates the string "false" as false:

function isBoolean($value) {
   if ($value && strtolower($value) !== "false") {
      return true;
   } else {
      return false;
   }
}

The documentation explains that: http://php.net/manual/en/language.types.boolean.php :

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
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

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