Parsing a string into a boolean in PHP

Today I played with PHP, and I found that the string values โ€‹โ€‹"true" and "false" are not correctly parsed into boolean in state, for example, by considering the following function:

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

If I do:

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

It seems to work only with the values โ€‹โ€‹"1" and "0":

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

Is there a built-in function in PHP for parsing the strings "true" and "false" in boolean?

+84
php parsing boolean
Jan 23 '11 at 17:38
source share
7 answers

There is a native PHP method that uses the PHP filter_var method:

 $bool = filter_var($value, FILTER_VALIDATE_BOOLEAN); 

According to the PHP 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-zero values.

+291
May 17 '12 at 23:54
source share

The reason is that all lines are evaluated to true when converting them to logical, except for "0" and "" (empty line).

The following function will do exactly what you want: it behaves exactly the same as PHP, but will also evaluate the string "false" to 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:

  • logical FALSE itself
  • integer 0 (zero)
  • float 0.0 (zero)
  • empty string and string "0"
  • array with zero elements
  • special type NULL (including undefined variables)
  • SimpleXML objects created from empty tags

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

+12
Jan 23 '11 at 17:40
source share

In PHP, only "0" or an empty forced string to false; every other non-empty line leads to true. From manual :

When converted to a boolean value, they are considered FALSE values:

  • empty string and string "0"

You need to write your own function to handle the string "true" vs "false" . Here, I assume that everything else is false by default:

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

On the side of the note, which can easily be reduced to

 function isBoolean($value) { return $value === "true"; } 
+4
Jan 23 '11 at 17:40
source share

I use this construct to convert strings to booleans, since you want true for most other values:

 $str = "true"; $bool = !in_array($str, array("false", "", "0", "no", "off")); 
+3
Jan 23 '11 at 17:50
source share

I recently needed a โ€œfreeโ€ boolean conversion function to process strings like the ones you are asking for (by the way). I found several different approaches and came up with a large set of test data to run them . Nothing was completely in line with my needs, so I wrote my own:

 function loosely_cast_to_boolean($value) { if(is_array($value) || $value instanceof Countable) { return (boolean) count($value); } else if(is_string($value) || is_object($value) && method_exists($value, '__toString')) { $value = (string) $value; // see http://www.php.net/manual/en/filter.filters.validate.php#108218 // see https://bugs.php.net/bug.php?id=49510 $filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if(!is_null($filtered)) { return $filtered; } else { // "none" gets special treatment to be consistent with ini file behavior. // see documentation in php.ini for more information, in part it says: // "An empty string can be denoted by simply not writing anything after // the equal sign, or by using the None keyword". if(strtolower($value) === 'none') { $value = ''; } return (boolean) $value; } } else { return (boolean) $value; } } 

Please note that for objects that are both countable and string, this will help count over the string value to determine the likelihood. That is, if $object instanceof Countable , this will return (boolean) count($object) regardless of the value of (string) $object .

You can see the behavior of the test data that I used, as well as the results for several other functions here . It's hard to see the results from this small iframe, so you can view the script output in a full page (the URL is undocumented instead, so this may not work forever). In case these links converge once, I also added pastebin code .

The line between what โ€œshould be trueโ€ and what should not be fairly arbitrary; The data I used is classified based on my needs and aesthetic preferences, yours may vary.

+2
Jul 16 '12 at 1:28
source share

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

No - both are strings, and both (as you say) evaluate to true . Only empty lines are evaluated to false in PHP.

You will need to check this manually. If at all possible, it would be better to work with โ€œrealโ€ Boolean values.

+1
Jan 23 '11 at 17:40
source share

The easiest way to safely convert to logical;

  $flag = 'true'; if( filter_var( $flag,FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ) !== null) { $flag = filter_var($flag,FILTER_VALIDATE_BOOLEAN); } gettype($flag); // Would Return 'Boolean' echo 'Val: '.$flag; // Would Output 'Val: 1' 
0
Mar 28 '13 at 15:17
source share



All Articles