325

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?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
tag
  • 3,315
  • 2
  • 16
  • 6
  • 1
    Newer use function ( (string) $param[boolean type] ){ if($param){....} } because (string) false => "false" is not false... – zloctb Oct 29 '15 at 08:54

16 Answers16

459

Simplest solution:

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

Player1
  • 2,878
  • 2
  • 26
  • 38
hobodave
  • 28,925
  • 4
  • 72
  • 77
  • 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 08 '10 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 '13 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. –  Jun 15 '14 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 '15 at 06:01
  • 5
    Note that you need extra brackets when you mix ternary operator and string concatenation. `echo '' . $res ? 'true' : 'false' . '';` does not produce desired result, `echo '' . ($res ? 'true' : 'false') . '';` does. – Salman A Mar 05 '18 at 08:33
263

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.

Mohammed H
  • 6,880
  • 16
  • 81
  • 127
Christian Davén
  • 16,713
  • 12
  • 64
  • 77
95

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"
Freez
  • 7,208
  • 2
  • 19
  • 29
  • 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 ;-) – Adam Cameron Mar 03 '16 at 09: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 '16 at 21:53
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"
treznik
  • 7,955
  • 13
  • 47
  • 59
16

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.

aleemb
  • 31,265
  • 19
  • 98
  • 114
  • `var_export()` seems to be the best for the specific use case, thanks. – Dr. Gianluigi Zane Zanettini Dec 10 '15 at 09: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". – faintsignal Nov 01 '16 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 06 '17 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 '17 at 19:56
  • In your fist line of code, you have: `$res = $res` ?? Did you mean: `$res == $res`? Or even: `$res === $res`? – SherylHohman Mar 01 '20 at 20:11
  • @SherylHohman No, it's assignment via a ternary operator. – BadHorsie Dec 02 '20 at 15:27
3

Why just don't do like this?:

if ($res) {
    $converted_res = "true";
}
else {
    $converted_res = "false";
}
xLite
  • 1,441
  • 3
  • 15
  • 28
good_evening
  • 21,085
  • 65
  • 193
  • 298
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'
asiby
  • 3,229
  • 29
  • 32
  • The example is wrong, `['false', 'true']` will provide the same output as the comments. – SeaWorld Sep 28 '21 at 02: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 '21 at 04: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 '21 at 08:03
  • Right. I have restored it. Thanks for the feedbacks – asiby Sep 30 '21 at 03:17
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.

dallin
  • 8,775
  • 2
  • 36
  • 41
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' : '').

motorbaby
  • 634
  • 7
  • 18
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' )  ); 
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237
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();        
    }
}
TarranJones
  • 4,084
  • 2
  • 38
  • 55
0
$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';
MERT DOĞAN
  • 2,864
  • 26
  • 28
  • `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. – ToolmakerSteve Feb 25 '19 at 02:20
0
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

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 "".

Julian
  • 4,396
  • 5
  • 39
  • 51
0

Try this:

 $value = !is_bool($value) ? $value : ( $value ? "true" : "false");
cstff
  • 123
  • 1
  • 9
-2

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

Reference Here.

atiquratik
  • 1,296
  • 3
  • 27
  • 34
Jesse
  • 386
  • 2
  • 8