Home >Backend Development >PHP Tutorial >How Can I Convert a Boolean to a 'true' or 'false' String in PHP?
Converting Boolean to String in PHP
Many PHP programmers encounter the challenge of converting a Boolean variable to a string in the format "true" or "false" instead of "0" or "1." To address this task effectively, let's explore the available methods.
One straightforward solution is to leverage the ternary operator. This method is both concise and efficient:
$converted_res = $res ? 'true' : 'false';
In this code, the ternary operator assigns "true" to $converted_res if $res is true, and "false" if $res is false. The ? and : symbols represent the conditional statement.
As an alternative approach, you can use the strval() function to convert the Boolean value to a string:
$converted_res = strval($res);
This method is particularly useful when you require a more generic string conversion that goes beyond the scope of True and False.
If you encounter errors related to unrecognized functions such as string() or String(), it's likely that your PHP installation doesn't have the "mbstring" extension enabled. To resolve this issue, enable the "mbstring" extension in your PHP configuration file (e.g., php.ini).
The above is the detailed content of How Can I Convert a Boolean to a 'true' or 'false' String in PHP?. For more information, please follow other related articles on the PHP Chinese website!