我有一个布尔变量,我想将其转换为字符串
$res = true;
Run Code Online (Sandbox Code Playgroud)
我需要它转换值也处于格式"true" "false"不"0" "1"
$converted_res = "true";
$converted_res = "false";
Run Code Online (Sandbox Code Playgroud)
我试过了:
$converted_res = string($res);
$converted_res = String($res);
Run Code Online (Sandbox Code Playgroud)
但它告诉我string并且String不是公认的功能.如何在php中将此布尔值转换为格式为"true"或"false"的字符串?
hob*_*ave 327
__PRE__
Chr*_*vén 179
函数var_export返回变量的字符串表示,因此您可以这样做:
var_export($res, true);
Run Code Online (Sandbox Code Playgroud)
第二个参数告诉函数返回字符串而不是回显它.
Fre*_*eez 54
另一种方法: json_encode( booleanValue )
echo json_encode(true); // string "true"
echo json_encode(false); // string "false"
// null !== false
echo json_encode(null); // string "null"
Run Code Online (Sandbox Code Playgroud)
dev*_*ler 35
请参见var_export
tre*_*nik 11
您可以使用strval()或(string)在PHP中转换为字符串.但是,这不会将布尔值转换为"true"或"false"的实际拼写,因此您必须自己执行此操作.这是一个示例函数:
function strbool($value)
{
return $value ? 'true' : 'false';
}
echo strbool(false); // "false"
echo strbool(true); // "true"
Run Code Online (Sandbox Code Playgroud)
这里的其他解决方案都有警告(虽然他们解决了手头的问题).如果您(1)循环使用混合类型或(2)想要一个可以作为函数导出或包含在您的实用程序中的通用解决方案,那么这里没有其他解决方案可行.
最简单,最不言自明的解决方案是:
// simplest, most-readable
if (is_bool($res) {
$res = $res ? 'true' : 'false';
}
// same as above but written more tersely
$res = is_bool($res) ? ($res ? 'true' : 'false') : $res;
// Terser still, but completely unnecessary function call and must be
// commented due to poor readability. What is var_export? What is its
// second arg? Why are we exporting stuff?
$res = is_bool($res) ? var_export($res, 1) : $res;
Run Code Online (Sandbox Code Playgroud)
但是大多数阅读代码的开发人员都需要访问http://php.net/var_export来了解var_export第二个参数的作用和内容.
var_export适用于boolean输入,但也将其他所有内容转换为a string.
// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1); // 'true'
// NOT OK
var_export('', 1); // '\'\''
// NOT OK
var_export(1, 1); // '1'
Run Code Online (Sandbox Code Playgroud)
($res) ? 'true' : 'false';适用于布尔输入,但将其他所有内容(整数,字符串)转换为true/false.
// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'
Run Code Online (Sandbox Code Playgroud)
json_encode()同样的问题var_export,可能更糟,因为json_encode无法知道字符串true是字符串还是布尔值.