Casting a string to boolean in PHP

So it’s been some time, but I finally came across an issue that I have faced, which hopefully means you have too. Either way this will serve as a great reference for myself, since I come across this on a semi-regular basis.

So say you are given data in the type of String, either from some sort of XML, JSON, or from user input that you need to convert to boolean. Using some quick logic you would think it was as easy as:

<?php
$string="false";
$string_boolean=(bool)$string;

right? Let’s try this one out:

<?php
$string="false";
$string_boolean=(bool)$string;
// note: you could use (bool) or (boolean) they do the same thing.
if ($string_boolean) {
    echo $string . " is true";
} else {
    echo $string . " is false";
}

If we run this script it returns, almost comically:

false is true

So what can we do here? Give up and change our career? Maybe. But let’s first do 2 things and then rethink our career-change:

  1. Why does this happen?
  2. What can we do about it?

Let’s examine PHP.net’s documentation regarding casting booleans.

From PHP.net:

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. 
However, in most cases the cast is unnecessary, since a value will be 
automatically converted if an operator, function or control structure requires 
a boolean argument.

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).

So, since both the string “true” and the string “false” do not meet any of the bullets, it will evaluate to true. OK, makes sense (sort of). So what are we to do now? Well we can create a function to mitigate our scenario. The function can be called string_boolean and what it can do is evaluate a string and if it’s value is “false” return false, otherwise return true. There is one gotchas that we need to mitigate, well it’s actually two: we need to treat “TRUE” , “TRue” ” TRUE”, ” True “, ”    TRUE”, etc. all as true and likewise we need to treat “FALSE”, “FALSe”, “FALSE  “, “False”, etc. all the same. We can make use of our two good function friends mb_strtoupper  (technically we could also use strtoupper) and trim.

So, let’s talk our way through this function. It’s signature would be function string_boolean ($string) and it’s body would basically clean up $string and evaluate it against the actual word “true” – if it equals true return TRUE (the boolean) otherwise return FALSE. This puts the onus on false, think of this as analogous to the concept of innocent until proven guilty. The value is false until it is proven in a trial (i.e. the function we create) to be true. This is a safer way to handle this in my estimation. We could use an if … then scheme, but I’d rather use our good old friend the ternary for the sake of brevity.

Let’s construct this baby (note I am purposely making this longer than it needs to be, for education’s sake. Don’t believe me, I’ll write the function’s body in one line before I’m done, that’ll teach you to go against me (just kidding)!):

function string_boolean($string){
	$string      = trim($string); // let's make sure we get rid of any junk whitespace surrounding our input.
	$string      = mb_strtoupper($string); // let's convert our input to uppercase, which will make our comparison easier.
	$true_string = mb_strtoupper("TRUE"); // just because I'm paranoid;
	return $string === $true_string ? TRUE : FALSE; //if processed input equals "TRUE" return true otherwise return false.
}

One quick note: I use === instead of == to be strict in my comparison. Since PHP is a weak typed language the === is a way to enforce testing both the TYPE and VALUE of $string. That is, === checks if the value of $string is equal to “TRUE” AND that both $string and “TRUE” are the same type (string). Hope that makes some semblance of sense.

Here is the function in one line!

function string_boolean($string){
	return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}

Enjoy!

6 Responses to “Casting a string to boolean in PHP”

  1. jack

    whats the best way print a boolean returned from a function

    Reply
  2. Denis

    function string_boolean($string){
    return mb_strtolower(trim($string)) === “true”;
    }

    Reply
    • Denis

      Or even

      function string_boolean($string){
      return !strcasecmp ( $string , “true” );
      }

      Reply
  3. Denis

    function boolean_string($boolean){
    return var_export($boolean, true);
    }

    or

    function boolean_string($boolean){
    return $boolean ? “true” : “false”;
    }

    Reply
  4. Shaun Doudican

    Try this:
    $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.

    Reply

Leave a Reply