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:

Download  Run Code

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():

Download  Run Code

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.

Download  Run Code

 
Also See:

Convert string to boolean in PHP

That’s all about converting boolean values to strings in PHP.