我有一个布尔变量,我想转换成一个字符串:
$res = true;
我需要转换值的格式为:“真”“假”,而不是“0”“1”
$converted_res = "true";
$converted_res = "false";
我试过了:
$converted_res = string($res);
$converted_res = String($res);
但它告诉我string和string不是被识别的函数。
如何将这个布尔值转换为PHP中“真”或“假”格式的字符串?
根据@sebastian-norr的建议编辑,指出$bool变量可能是真0或真1,也可能不是。例如,在PHP中运行布尔测试时,2解析为true。
作为解决方案,我使用了类型强制转换来确保将$bool转换为0或1。
但我必须承认,简单的表达式$bool ?'true': 'false'简洁得多。
我下面使用的解决方案永远不应该使用,哈哈。
为什么不呢?
为了避免重复,包含布尔值的字符串表示形式的数组可以存储在一个常量中,该常量可以在整个应用程序中使用。
// Make this constant available everywhere in the application
const BOOLEANS = ['false', 'true'];
$bool = true;
echo BOOLEANS[(bool) $bool]; // 'true'
echo BOOLEANS[(bool) !$bool]; // 'false'