如何将布尔值转换为字符串

2022-08-30 06:05:12

我有一个布尔变量,我想将其转换为字符串:

$res = true;

我需要转换后的值的格式为:,而不是"true" "false""0" "1"

$converted_res = "true";
$converted_res = "false";

我试过了:

$converted_res = string($res);
$converted_res = String($res);

但它告诉我,并且不是公认的功能。
如何将此布尔值转换为PHP格式或PHP格式的字符串?stringString"true""false"


答案 1

最简单的解决方案:

$converted_res = $res ? 'true' : 'false';


答案 2

函数var_export返回变量的字符串表示形式,因此您可以执行以下操作:

var_export($res, true);

第二个参数告诉函数返回字符串,而不是回显它。


推荐