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\"
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();
}
}