How to Convert Boolean to String

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

    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.

提交回复
热议问题