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

$res = true;

我需要转换值的格式为:“真”“假”,而不是“0”“1”

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

我试过了:

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

但它告诉我string和string不是被识别的函数。 如何将这个布尔值转换为PHP中“真”或“假”格式的字符串?


当前回答

这里的其他解决方案都有注意事项(尽管它们解决了当前的问题)。如果你(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;

但是大多数阅读您的代码的开发人员需要访问http://php.net/var_export来理解var_export做什么以及第二个参数是什么。

1. var_export

适用于布尔输入,但也将其他所有内容转换为字符串。

// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1);  // 'true'
// NOT OK
var_export('', 1);  // '\'\''
// NOT OK
var_export(1, 1);  // '1'

2. (res) ?'true': 'false';

适用于布尔输入,但将其他所有内容(int,字符串)转换为true/false。

// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'

3.json_encode ()

与var_export相同的问题,可能更糟,因为json_encode无法知道字符串true是字符串还是布尔值。

其他回答

最简单的解决方案:

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

试试这个:

 $value = !is_bool($value) ? $value : ( $value ? "true" : "false");

在PHP中使用strval()或(string)转换为字符串。 但是,这并不能将布尔值转换为“true”或“false”的实际拼写,所以您必须自己完成。 下面是一个示例函数:

function strbool($value)
{
    return $value ? 'true' : 'false';
}
echo strbool(false); // "false"
echo strbool(true); // "true"

为什么不这样做呢?:

if ($res) {
    $converted_res = "true";
}
else {
    $converted_res = "false";
}

只是想更新一下,在PHP >= 5.50中,你可以使用boolval()来做同样的事情

参考这里。