333

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?

1
  • 1
    Newer use function ( (string) $param[boolean type] ){ if($param){....} } because (string) false => "false" is not false...
    – zloctb
    Oct 29, 2015 at 8:54

16 Answers 16

464

Simplest solution:

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

5
  • 2
    This is the easyest way to do it, but it depends on what you need it for it might not be the best sulution.
    – Androme
    May 8, 2010 at 18:43
  • 1
    @DoomStone I know it's been 3 years, but I just wanted to know what makes you think in some cases it's not the best solution. The ?: notation is the most simplified code we can come up with in this situation.
    – caiosm1005
    Jul 14, 2013 at 23:39
  • 3
    For example for me, it is not the best solution for the case at hand: I am not sure what the type of the return value is; it may be boolean or something else. (Calling a function someone else wrote during debugging.) Your solution converts $res to boolean, whereas var_export can handle all possible types.
    – user2443147
    Jun 15, 2014 at 18:47
  • 17
    @user2443147 the type being boolean is literally the first fact mentioned in the question. If you are not sure about the type you are dealing with, you have a whole other set of problems to begin with.
    – nem75
    May 20, 2015 at 6:01
  • 5
    Note that you need extra brackets when you mix ternary operator and string concatenation. echo '<active>' . $res ? 'true' : 'false' . '</active>'; does not produce desired result, echo '<active>' . ($res ? 'true' : 'false') . '</active>'; does.
    – Salman A
    Mar 5, 2018 at 8:33
267

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.

1
  • 5
    Perfect answer. This is the "PHP" way of getting a "...a parsable string representation of a variable" Sep 30, 2019 at 8:17
96

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"
2
  • 9
    I think semantically using var_export() is more in-keeping with the intent of the operation (unless one is needing the string for some JSON, that is ;-) Mar 3, 2016 at 9:42
  • 3
    This really relies on the side-effect that the JSON representation happens to be the same as what is wanted. It also relies on the JSON extension being installed and enabled, which might be very likely but isn't a given. So imho this isn't a clean solution.
    – Nick Rice
    Apr 29, 2016 at 21:53
17

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.

6
  • var_export() seems to be the best for the specific use case, thanks. Dec 10, 2015 at 9:51
  • For PHP 5.5+ installations, var_export(boolval($var), true) is a safe way route to transform the value into the strings "true" or "false". Nov 1, 2016 at 15:29
  • if (is_bool($res) { $res = $res ? 'true' : 'false'; } << this won't work - missing ) perhaps its better to use $result = (is_bool($var) && $var) ? 'true' : 'false';
    – mtizziani
    Feb 6, 2017 at 11:18
  • @aleemb What about: $value = is_bool($value) ? var_export($value, true) : $value; This way I live the value intact and only change the boolean to their string representation.
    – dickwan
    Mar 14, 2017 at 19:56
  • In your fist line of code, you have: $res = $res ?? Did you mean: $res == $res? Or even: $res === $res? Mar 1, 2020 at 20:11
16

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"
1
  • If $val = true; then strval($val) and (string) $val both return 1.
    – ABach
    May 8, 2010 at 18:34
3

Why just don't do like this?:

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

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.

2

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 = ['false', 'true'];

$bool = true;
echo BOOLEANS[(bool)  $bool]; // 'true'
echo BOOLEANS[(bool) !$bool]; // 'false'
4
  • The example is wrong, ['false', 'true'] will provide the same output as the comments.
    – SeaWorld
    Sep 28, 2021 at 2:56
  • Thanks. You are right. I have even detected another error. The type casting should have been done in int instead of bool. Also, I have reversed the BOOLEANS array.
    – asiby
    Sep 28, 2021 at 4:12
  • I think they should stay type cast to a bool. Main reason being that if someone were to encounter let's say $bool = 2; then with boolean logic being considered, that would be true, since anything more than or equal to 1 is true.
    – SeaWorld
    Sep 28, 2021 at 8:03
  • Right. I have restored it. Thanks for the feedbacks
    – asiby
    Sep 30, 2021 at 3:17
1

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' : '').

1
  • 1
    When does boolval(some_expression) ? .. : .. behave differently than some_expression ? .. : ..? Feb 25, 2019 at 2:23
1

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' )  ); 
}
0

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();        
    }
}
0
$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';
1
  • isset not necessary here. In php, if-test is false for both null and variable not defined. Can simply do $converted_res = ( $res ? 'true' : 'false' ); as seen in older answers. Feb 25, 2019 at 2:20
0

How about converting to integer, then to string?

$ php -a
Interactive mode enabled

php > $a = true;
php > $b = false;
php > $c = (string)(int)$a;
php > $d = (string)(int)$b;
php > var_dump($c);
string(1) "1"
php > var_dump($d);
string(1) "0"
php >

What happens if you convert a boolean directly to string?

$ php -a
Interactive mode enabled

php > $a = true;
php > $b = false;
php > $c = (string)$a;
php > $d = (string)$b;
php > var_dump($c);
string(1) "1"
php > var_dump($d);
string(0) ""
php >

Converting a false to string will produce an empty string "".

0

Try this:

 $value = !is_bool($value) ? $value : ( $value ? "true" : "false");
-1
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)
-2

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

Reference Here.

3
  • 3
    This is the same as using (bool) $var;
    – Al.G.
    Jul 7, 2015 at 10:17
  • Thank you! This worked for me in a complicated table. Used it like this: "<td>" . (boolval($row['special_case']) ? 'Yes' : ' ') . "</td>"
    – motorbaby
    Jan 3, 2017 at 1:07
  • 5
    boolval() goes the other way, converting a variable of any type to bool, not bool to string. May 15, 2017 at 2:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.