I have a Boolean variable which I want to convert to a string:
$res = true;
I need the converted value to be of the format: \"true\"
Another way to do : json_encode( booleanValue )
echo json_encode(true); // string "true"
echo json_encode(false); // string "false"
// null !== false
echo json_encode(null); // string "null"
For me, I wanted a string representation unless it was null
, in which case I wanted it to remain null
.
The problem with var_export is it converts null
to a string "NULL"
and it also converts an empty string to "''"
, which is undesirable. There was no easy solution that I could find.
This was the code I finally used:
if (is_bool($val)) $val ? $val = "true" : $val = "false";
else if ($val !== null) $val = (string)$val;
Short and simple and easy to throw in a function too if you prefer.
See var_export
This works also for any kind of value:
$a = true;
echo $a // outputs: 1
echo value_To_String( $a ) // outputs: true
code:
function valueToString( $value ){
return ( !is_bool( $value ) ? $value : ($value ? 'true' : 'false' ) );
}
The other solutions here all have caveats (though they address the question at hand). If you are (1) looping over mixed-types or (2) want a generic solution that you can export as a function or include in your utilities, none of the other solutions here will work.
The simplest and most self-explanatory solution is:
// simplest, most-readable
if (is_bool($res) {
$res = $res ? 'true' : 'false';
}
// same as above but written more tersely
$res = is_bool($res) ? ($res ? 'true' : 'false') : $res;
// Terser still, but completely unnecessary function call and must be
// commented due to poor readability. What is var_export? What is its
// second arg? Why are we exporting stuff?
$res = is_bool($res) ? var_export($res, 1) : $res;
But most developers reading your code will require a trip to http://php.net/var_export to understand what the var_export
does and what the second param is.
var_export
Works for boolean
input but converts everything else to a string
as well.
// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1); // 'true'
// NOT OK
var_export('', 1); // '\'\''
// NOT OK
var_export(1, 1); // '1'
($res) ? 'true' : 'false';
Works for boolean input but converts everything else (ints, strings) to true/false.
// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'
json_encode()
Same issues as var_export
and probably worse since json_encode
cannot know if the string true
was intended a string or a boolean.
$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';