How to Convert Boolean to String
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" "false"
, not "0" "1"
$converted_res = "true";
$converted_res = "false";
I've tried:
$converted_res = string($res);
$converted_res = String($res);
But it tells me that string
and String
are not recognized functions.
How do I convert this Boolean to a string in the format of "true"
or "false"
in PHP?
Solution 1:
Simplest solution:
$converted_res = $res ? 'true' : 'false';
Solution 2:
The function var_export returns a string representation of a variable, so you could do this:
var_export($res, true);
The second argument tells the function to return the string instead of echoing it.
Solution 3:
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"
Solution 4:
See var_export