Current Location: Home> Latest Articles> PHP Boolean Type Conversion Guide: How to Correctly Convert bool Data

PHP Boolean Type Conversion Guide: How to Correctly Convert bool Data

M66 2025-07-26

How to Convert Boolean Type to Integer

In PHP, boolean values (true or false) can be converted to integers either through type casting or using built-in functions. Below are two common conversion methods:

// Using (int) for type casting
$boolValue = true;
$intValue = (int)$boolValue;
echo $intValue;  // Output: 1

// Using intval() function for conversion
$boolValue = false;
$intValue = intval($boolValue);
echo $intValue;  // Output: 0

How to Convert Boolean Type to String

Similarly, boolean values can also be converted to strings, typically using type casting or the strval() function. Below is the example:

// Using (string) for type casting
$boolValue = true;
$strValue = (string)$boolValue;
echo $strValue;  // Output: "1"

// Using strval() function for conversion
$boolValue = false;
$strValue = strval($boolValue);
echo $strValue;  // Output: an empty string ""

Details to Pay Attention to During Conversion

It’s important to be cautious during type conversion to avoid unexpected results. For instance, when converting the string "false" to a boolean, it will be interpreted as true, not false. This is because PHP treats any non-empty string as true. Therefore, developers should choose the right conversion method based on the specific scenario to ensure the accuracy of the program logic.

Conclusion

Properly converting boolean values to other types is crucial for the stability and maintainability of PHP code. The examples and tips provided in this article will help developers understand and master boolean type conversion techniques, enabling them to write more robust programs.