Parsing a string into a boolean value in PHP

Mark picture Mark · Jan 23, 2011 · Viewed 82.2k times · Source

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?

Answer

Eric Caron picture Eric Caron · May 18, 2012

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.