0

Is there a PHP function that shows a textual version of the boolean setting of "1" as "True" or "On", etc.?

I know how to use if() statements to make it happen, but I searched and could not find anything that might be a shortcut to achieve this.

Thanks.

H. Ferrence
  • 7,906
  • 31
  • 98
  • 161
  • i dont know if you would call it a shortcut, but json_encode() does exactly that. the function provided in Rawkode answer is faster and more clean, you should use that – x4rf41 Feb 27 '13 at 13:15
  • 1
    Possible duplicate > http://stackoverflow.com/questions/2795177/how-to-convert-boolean-to-string – BenM Feb 27 '13 at 13:17
  • You're right @BenM .. it was asked and answered before. Thanks for linking. – H. Ferrence Feb 27 '13 at 13:21
  • Unfortunately the accepted answer to that question is right, but not the "rightest" one... – ExternalUse Feb 27 '13 at 13:43

2 Answers2

3

You're looking for var_export:

var_export(true, true) : string = "true"

If you have an integer value, you can use type juggling beforehand:

var_export((bool) 1, true)
: string = "true"
var_export((bool) 0, true)
: string = "false"

Please see the chapter on type juggling http://php.net/manual/en/language.types.type-juggling.php before you attempt to run this with the Strings "On" and "Off" - the first one will evaluate to true, the latter one to - guess! (I'll help, it's true as well). So beware. An empty string however would be casted to false.

ExternalUse
  • 2,053
  • 2
  • 25
  • 37
  • It was my understanding of the question that the author wanted a function to convert boolean values to text, such as True or On and not to determine a boolean value for the text itself. – Rawkode Feb 27 '13 at 13:25
  • Well, var_export does exactly that. As you can see the result is a string (which in my understanding is text). See the manual for var_export, especially the second "return" parameter: "If used and set to TRUE, var_export() will return the variable representation instead of outputing it." – ExternalUse Feb 27 '13 at 13:38
1
function boolToText($bool) {
  return $bool ? 'True' : 'False';
}
Rawkode
  • 21,990
  • 5
  • 38
  • 45