Convert boolean to string in PHP
This article demonstrates how to convert boolean values to strings in PHP.
1. Using identity operator
The standard solution to convert a value to a string is to use the (string)
cast or the strval()
function. However, it converts the boolean true
value to the string "1"
and the boolean false
value to an empty string (""
).
You can use the identity comparison operator to convert the boolean values true
and false
to the string "true"
and "false"
respectively. The ===
operator evaluates to true
if both operands are equal and have the same type. The idea is to simply compare your variable against boolean true
and false
with ===
and return the corresponding string value, as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php function bool_to_str($val) { if ($val === true) { return 'true'; } if ($val === false) { return 'false'; } return $val; } $val = true; $res = bool_to_str($val); var_dump($res); // string(4) "true" $val = false; $res = bool_to_str($val); var_dump($res); // string(5) "false" ?> |
2. Using var_export()
function
You can get the string representation of a variable using the var_export()
function. If the second parameter is set to true, var_export()
returns the string representation instead of outputting it. For example, the strings "true"
and "false"
are returned when boolean values true
and false
are passed to var_export()
:
1 2 3 4 5 6 7 8 9 10 |
<?php $val = true; $res = var_export($val, true); var_dump($res); // string(4) "true" $val = false; $res = var_export($val, true); var_dump($res); // string(5) "false" ?> |
3. Using json_encode()
function
Finally, you can use the json_encode()
function to convert a boolean to a string. It returns a string containing the JSON representation of the specified value. If the parameter is of the scalar type, json_encode()
generates a JSON that is a simple value (i.e., neither an object nor an array). For boolean values true
and false
, the string "true"
and "false"
is returned.
1 2 3 4 5 6 7 8 9 10 |
<?php $val = true; $res = json_encode($val); var_dump($res); // string(4) "true" $val = false; $res = json_encode($val); var_dump($res); // string(5) "false" ?> |
Also See:
That’s all about converting boolean values to strings in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)