This tutorial will discuss multiple ways to check if string is boolean in PHP.
Table Of Contents
Method 1: Using strict comparison
To check if a string contains a boolean value, we can follow these steps:
First, we need to convert the given string to lowercase using the strtolower() function. This ensures case-insensitive comparison. Then, we check if the lowercase string is equal to either “true” or “false”. If it matches either of these values, it means that the string contains a boolean value.
We have created a separate function for this purpose.
function isBooleanString($strValue) { return strtolower($strValue) === 'true' || strtolower($strValue) === 'false'; }
It accepts a string as an argument and returns true if the given string is a boolean value.
Let’s see the complete example,
Frequently Asked:
<?php /** * Check if a string represents a boolean value. * * @param string $strValue The string to validate. * @return bool True if the string represents a boolean value, false otherwise. */ function isBooleanString($strValue) { return strtolower($strValue) === 'true' || strtolower($strValue) === 'false'; } $strValue = 'true'; // Check if string contains a Valid Boolean Value if (isBooleanString($strValue)) { echo "The string represents a boolean value."; } else { echo "The string does not represent a boolean value."; } ?>
Output
The string represents a boolean value.
Method 2: Using filter_var() function
We can also use the filter_var() function with the FILTER_VALIDATE_BOOLEAN filter. By passing the string as the first argument and FILTER_VALIDATE_BOOLEAN as the second argument, the function will return true if the string contains a boolean value.
Let’s see the complete example,
<?php /** * Check if a string represents a boolean value. * * @param string $strValue The string to validate. * @return bool True if the string represents a boolean value, false otherwise. */ function isBoolean($strValue) { return filter_var( $strValue, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null; } $strValue = 'false'; // Check if string contains a Valid Boolean Value if (isBoolean($strValue)) { echo "The string represents a boolean value."; } else { echo "The string does not represent a boolean value."; } ?>
Output
The string represents a boolean value.
Summary
Today, we learned about multiple ways to check if string is boolean in PHP.