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

$res = true;

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

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

我试过了:

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

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


当前回答

另一种方法:json_encode(booleanValue)

echo json_encode(true);  // string "true"

echo json_encode(false); // string "false"

// null !== false
echo json_encode(null);  // string "null"

其他回答

最简单的解决方案:

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

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

Boolval()适用于复杂的表,其中声明变量和添加循环和过滤器都不起作用。例子:

$result[$row['name'] . "</td><td>" . (boolval($row['special_case']) ? 'True' : 'False') . "</td><td>" . $row['more_fields'] = $tmp

其中$tmp是用于转置其他数据的键。在这里,我想表显示“是”为1和0,所以使用(boolval($row['special_case']) ?“是”:)。

这也适用于任何类型的价值:

$a = true;

echo $a                     // outputs:   1
echo value_To_String( $a )  // outputs:   true

代码:

function valueToString( $value ){ 
    return ( !is_bool( $value ) ?  $value : ($value ? 'true' : 'false' )  ); 
}

根据@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'