How to Convert Boolean to String

后端 未结 15 665
死守一世寂寞
死守一世寂寞 2020-11-28 02:43

I have a Boolean variable which I want to convert to a string:

$res = true;

I need the converted value to be of the format: \"true\"

相关标签:
15条回答
  • 2020-11-28 03:27

    Edited based on @sebastian-norr suggestion pointing out that the $bool variable may or may not be a true 0 or 1. For example, 2 resolves to true when running it through a Boolean test in PHP.

    As a solution, I have used type casting to ensure that we convert $bool to 0 or 1.
    But I have to admit that the simple expression $bool ? 'true' : 'false' is way cleaner.

    My solution used below should never be used, LOL.
    Here is why not...

    To avoid repetition, the array containing the string representation of the Boolean can be stored in a constant that can be made available throughout the application.

    // Make this constant available everywhere in the application
    const BOOLEANS = ['true', 'false'];
    
    $bool = true;
    echo BOOLEANS[(bool)  $bool]; // 'true'
    echo BOOLEANS[(bool) !$bool]; // 'false'
    
    0 讨论(0)
  • 2020-11-28 03:28

    The function var_export returns a string representation of a variable, so you could do this:

    var_export($res, true);
    

    The second argument tells the function to return the string instead of echoing it.

    0 讨论(0)
  • 2020-11-28 03:28
    function ToStr($Val=null,$T=0){
    
        return is_string($Val)?"$Val"
        :
        (
            is_numeric($Val)?($T?"$Val":$Val)
            :
            (
                is_null($Val)?"NULL"
                :
                (
                    is_bool($Val)?($Val?"TRUE":"FALSE")
                    :
                    (
                        is_array($Val)?@StrArr($Val,$T)
                        :
                        false
                    )
                )
            )
        );
    
    }
    function StrArr($Arr,$T=0)
    {
        $Str="";
        $i=-1;
        if(is_array($Arr))
        foreach($Arr AS $K => $V)
        $Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
        return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
    }
    
    $A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
    echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)
    
    0 讨论(0)
提交回复
热议问题