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\"
Just wanted to update, in PHP >= 5.50 you can do boolval()
to do the same thing
Reference Here.
boolval()
works for complicated tables where declaring variables and adding loops and filters do not work. Example:
$result[$row['name'] . "</td><td>" . (boolval($row['special_case']) ? 'True' : 'False') . "</td><td>" . $row['more_fields'] = $tmp
where $tmp
is a key used in order to transpose other data. Here, I wanted the table to display "Yes" for 1 and nothing for 0, so used (boolval($row['special_case']) ? 'Yes' : '')
.
I'm not a fan of the accepted answer as it converts anything which evaluates to false to "false"
no just boolean and vis-versa.
Anyway here's my O.T.T answer, it uses the var_export function.
var_export
works with all variable types except resource
, I have created a function which will perform a regular cast to string ((string)
), a strict cast (var_export
) and a type check, depending on the arguments provided..
if(!function_exists('to_string')){
function to_string($var, $strict = false, $expectedtype = null){
if(!func_num_args()){
return trigger_error(__FUNCTION__ . '() expects at least 1 parameter, 0 given', E_USER_WARNING);
}
if($expectedtype !== null && gettype($var) !== $expectedtype){
return trigger_error(__FUNCTION__ . '() expects parameter 1 to be ' . $expectedtype .', ' . gettype($var) . ' given', E_USER_WARNING);
}
if(is_string($var)){
return $var;
}
if($strict && !is_resource($var)){
return var_export($var, true);
}
return (string) $var;
}
}
if(!function_exists('bool_to_string')){
function bool_to_string($var){
return func_num_args() ? to_string($var, true, 'boolean') : to_string();
}
}
if(!function_exists('object_to_string')){
function object_to_string($var){
return func_num_args() ? to_string($var, true, 'object') : to_string();
}
}
if(!function_exists('array_to_string')){
function array_to_string($var){
return func_num_args() ? to_string($var, true, 'array') : to_string();
}
}
Simplest solution:
$converted_res = $res ? 'true' : 'false';
You use strval() or (string) to convert to string in PHP. However, that does not convert boolean into the actual spelling of "true" or "false" so you must do that by yourself. Here's an example function:
function strbool($value)
{
return $value ? 'true' : 'false';
}
echo strbool(false); // "false"
echo strbool(true); // "true"
Why just don't do like this?:
if ($res) {
$converted_res = "true";
}
else {
$converted_res = "false";
}