How to Convert Boolean to String

后端 未结 15 751
死守一世寂寞
死守一世寂寞 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:15

    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.

提交回复
热议问题