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'