views:

84

answers:

1

When echoing a boolean (true or false), PHP converts it to 1 or <nothing> and displays it. e.g.:

$x = true; echo $x; //displays: 1
$x = false; echo $x; //displays: <nothing>

My Question: Is there a PHP function (if not how to code it) which can display exactly "true" or "false" (and not 1 or nothing), if a variable is a boolean otherwise just display as PHP would normally display it.

+3  A: 

Yes, it can be easily coded like this:

function var_to_str($in)
{
   if(is_bool($in))
   {
      if($in)
         return "true";
      else
         return "false";
   }
   else
      return $in;
}

//Test it now
echo var_to_str("this is string") . PHP_EOL;
echo var_to_str(123) . PHP_EOL;
echo var_to_str(true) . PHP_EOL;
echo var_to_str(false) . PHP_EOL;

This outputs:

this is string  
123  
true  
false  
shamittomar