In this tutorial, we will cover one of the fundamental methods in PHP to determine whether a given variable is a Boolean value or not.
Variable evaluation refers to the method of determining whether a given PHP variable is a specific type or within a given string or expression.
Variable evaluation is a fantastic feature is it can allow you to quickly process and evaluate whether a given user input is a specific type or not. This can help you sanitize user data and prevent malicious content from passing through.
PHP is_bool() Function
As the name suggests, the is_bool()
method allows to determine whether a given input is a Boolean Value or not.
The function syntax is as shown below:
is_bool(mixed $value): bool
The function accepts only one parameter:
value
- this refers to the value whose type you wish to evaluate.
The function returns a Boolean True
is the input is bool
type and False
if otherwise.
Examples
The following example demonstrates how to use the is_bool()
method to check if a given variable is a Boolean Type.
$my_var = true;
if (is_bool($my_var)) {
echo "The variable is a boolean value.";
} else {
echo "The variable is not a boolean value.";
}
Output:
The variable is a boolean value.
Example 2
We can also use the is_bool()
method to check if the return value of a given function is a boolean as demonstrated in the snippet below:
function is_active($user) {
// some code to check if the user is active
return true;
}
if (is_bool(is_active("Peter"))) {
echo "The function returned a boolean value.";
} else {
echo "The function did not return a boolean value.";
}
Output:
The function returned a boolean value.
Example 3
We can also use the is_bool()
method to validate user input as demonstrated in the code below:
$user_input = "true";
if (is_bool($user_input)) {
echo "The input is a boolean value.";
} else {
echo "The input is not a boolean value.";
}
Resulting output:
The input is not a boolean value.
In this case, the is_bool()
function returns false
asthe value of $user_input
is a string, not a boolean value.
Conclusion
In this post, we discussed how to work with the is_bool()
function to perform a variety of tasks. For example, we discussed to validate a function return value. We also used it to validate the user input.