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\"
Edited based on @sebastian-norr suggestion pointing out that the $bool
variable may or may not be a true 0
or 1
. For example, 2
resolves to true
when running it through a Boolean test in PHP.
As a solution, I have used type casting to ensure that we convert $bool
to 0
or 1
.
But I have to admit that the simple expression $bool ? 'true' : 'false'
is way cleaner.
My solution used below should never be used, LOL.
Here is why not...
To avoid repetition, the array containing the string representation of the Boolean can be stored in a constant that can be made available throughout the application.
// Make this constant available everywhere in the application
const BOOLEANS = ['true', 'false'];
$bool = true;
echo BOOLEANS[(bool) $bool]; // 'true'
echo BOOLEANS[(bool) !$bool]; // 'false'
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.
function ToStr($Val=null,$T=0){
return is_string($Val)?"$Val"
:
(
is_numeric($Val)?($T?"$Val":$Val)
:
(
is_null($Val)?"NULL"
:
(
is_bool($Val)?($Val?"TRUE":"FALSE")
:
(
is_array($Val)?@StrArr($Val,$T)
:
false
)
)
)
);
}
function StrArr($Arr,$T=0)
{
$Str="";
$i=-1;
if(is_array($Arr))
foreach($Arr AS $K => $V)
$Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
}
$A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)