The first idea that comes into mind for doing this is to simply make a typecast of the boolean variable to a string and use that (which works)
$testVar = false; echo (string)$testVar; //will output a empty string (as that evaluates to false) $testVar = true; echo (string)$testVar; //will output 1 (as that evaluates to true)
but what if the requirement is that the string should say true or false
$testVar = false; echo $testVar ? 'true' : 'false'; //will output false $testVar = true; echo $testVar ? 'true' : 'false'; //will output true
(While the above example might seam useless I recently had to do this for a db insert)
Hi,
In case you need to output a boolean as string concatenated with
another string:
$test_var = false;
echo “\$test_var is: ” . ($test_var ? ‘true’ : ‘false’) . “.”; // will output ‘$test_var is: false.
echo “\n”;
$test_var = true;
echo “\$test_var is: ” . ($test_var ? ‘true’ : ‘false’) . “.”; // will output $test_var is: true.
Deleting the parentheses results in a significant change in the output (which I can’t explain): $test_var is: true.