[php] How to Convert Boolean to String

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" "false", not "0" "1"

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

I've tried:

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

But it tells me that string and String are not recognized functions.
How do I convert this Boolean to a string in the format of "true" or "false" in PHP?

This question is related to php string

The answer is


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)

You use strval() or (string) to convert to string in PHP. However, that does not convert boolean into the actual spelling of "true" or "false" so you must do that by yourself. Here's an example function:

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

The other solutions here all have caveats (though they address the question at hand). If you are (1) looping over mixed-types or (2) want a generic solution that you can export as a function or include in your utilities, none of the other solutions here will work.

The simplest and most self-explanatory solution is:

// 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;

But most developers reading your code will require a trip to http://php.net/var_export to understand what the var_export does and what the second param is.

1. var_export

Works for boolean input but converts everything else to a string as well.

// 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';

Works for boolean input but converts everything else (ints, strings) to 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()

Same issues as var_export and probably worse since json_encode cannot know if the string true was intended a string or a boolean.



This works also for any kind of value:

$a = true;

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

code:

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

For me, I wanted a string representation unless it was null, in which case I wanted it to remain null.

The problem with var_export is it converts null to a string "NULL" and it also converts an empty string to "''", which is undesirable. There was no easy solution that I could find.

This was the code I finally used:

if (is_bool($val)) $val ? $val = "true" : $val = "false";
else if ($val !== null) $val = (string)$val;

Short and simple and easy to throw in a function too if you prefer.


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.


$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';

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'

Why just don't do like this?:

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

boolval() works for complicated tables where declaring variables and adding loops and filters do not work. Example:

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

where $tmp is a key used in order to transpose other data. Here, I wanted the table to display "Yes" for 1 and nothing for 0, so used (boolval($row['special_case']) ? 'Yes' : '').


Just wanted to update, in PHP >= 5.50 you can do boolval() to do the same thing

Reference Here.


Another way to do : json_encode( booleanValue )

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

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

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

I'm not a fan of the accepted answer as it converts anything which evaluates to false to "false" no just boolean and vis-versa.

Anyway here's my O.T.T answer, it uses the var_export function.

var_export works with all variable types except resource, I have created a function which will perform a regular cast to string ((string)), a strict cast (var_export) and a type check, depending on the arguments provided..

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();        
    }
}