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

$res = true;

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

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

我试过了:

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

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


当前回答

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']) ?“是”:)。

其他回答

我不是公认的答案的粉丝,因为它将任何计算为假的东西转换为“假”,不只是布尔和反之亦然。

不管怎样,这是我的O.T.T答案,它使用var_export函数。

var_export适用于所有变量类型,除了资源,我已经创建了一个函数,它将执行常规转换为字符串((字符串)),严格转换(var_export)和类型检查,取决于提供的参数。

if(!function_exists('to_string')){

    function to_string($var, $strict = false, $expectedtype = null){

        if(!func_num_args()){
            return trigger_error(__FUNCTION__ . '() expects at least 1 parameter, 0 given', E_USER_WARNING);
        }
        if($expectedtype !== null  && gettype($var) !== $expectedtype){
            return trigger_error(__FUNCTION__ . '() expects parameter 1 to be ' . $expectedtype .', ' . gettype($var) . ' given', E_USER_WARNING);
        }
        if(is_string($var)){
            return $var;
        }
        if($strict && !is_resource($var)){
            return var_export($var, true);
        }
        return (string) $var;
    }
}

if(!function_exists('bool_to_string')){

    function bool_to_string($var){
        return func_num_args() ? to_string($var, true, 'boolean') : to_string();        
    }
}

if(!function_exists('object_to_string')){

    function object_to_string($var){
        return func_num_args() ? to_string($var, true, 'object') : to_string();        
    }
}

if(!function_exists('array_to_string')){

    function array_to_string($var){
        return func_num_args() ? to_string($var, true, 'array') : to_string();        
    }
}

根据@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'
$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';

最简单的解决方案:

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

另一种方法:json_encode(booleanValue)

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

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

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