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

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

其他回答

最简单的解决方案:

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

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

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

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

不管怎样,这是我的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();        
    }
}

为什么不这样做呢?:

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

试试这个:

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