5

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.

4 Answers 4

8

I've just been looking to do this but needed to to it inline without a function so I just used :

echo(is_bool($x) ? ($x ? "true":"false"):$x);

Not the easiest to read but gets the job done!

Sign up to request clarification or add additional context in comments.

Comments

7

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  

Comments

1
str_replace(array(0, 1), array("No", "Yes"), str_pad(headers_sent(), 1, "0"))

I used headers_sent() just as a BOOLEAN variable.

Comments

0

I had this issue, found this question and the answer was not quite what I needed, so I worked out this:

array_pop(array_keys(array('FALSE' => false,'TRUE' => true), [bool]))

to simply get a printed (echoed) string value for a [bool], replacing [bool] with a variable you know to be a bool.

Thought it might help others who find this question....

1 Comment

That would work, but a serious performance hit. Better write a function that returns the appropriate string for the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.