FILTER_VALIDATE_BOOLEAN

$var="Off";
var_dump(filter_var($var, FILTER_VALIDATE_BOOLEAN));
Here is a list of outputs we will get for different data stored in variable.
$var="Yes"; // bool(true)
$var="1"; // bool(true)
$var="on"; // bool(true)
$var="True"; // bool(true)

$var="T"; // bool(false)
$var="0"; // bool(false)
$var="False"; // bool(false)
$var=""; // bool(false)
$var="abcd"; // bool(false)
$var="Off"; // bool(false)
$var="no"; // bool(false)
FILTER_VALIDATE_BOOLEAN filter can check the variable Boolean or not. We will use var_dump function to know more about the variable returned.

For different value of Boolean variable we will get this output. You can see we get bool(false) for non Boolean value. Now we will add one option FILTER_NULL_ON_FAILURE to get null value for all non Boolean variables. Here is the code
$var="Off";
var_dump(filter_var($var, FILTER_VALIDATE_BOOLEAN,FILTER_NULL_ON_FAILURE));
The output for different value of the variable is listed here for easy understanding.
$var="abcd"; // NULL
$var=""; // NULL
$var="T"; // NULL

$var="1"; // bool(true)
$var="on"; // bool(true)
$var="True"; // bool(true)
$var="Yes"; // bool(true)

$var="False"; // bool(false)
$var="0"; // bool(false)
$var="no"; // bool(false)
$var="Off"; // bool(false)
As you can see we are getting NULL value for all non boolean values.

Example: Handling Non-Standard Boolean Values

$value = "yes";
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
echo $result === null ? "Invalid" : ($result ? "True" : "False");
// Output: True

Example: Custom Boolean Validation for Non-Typical Inputs

function custom_boolean($value) {
    return in_array(strtolower($value), ['true', '1', 'on', 'yes'], true);
}
echo custom_boolean("Yes") ? "True" : "False";  // Output: True

Filter reference Validating URL Ctype_alnum to check alphanumeric characters Validating Email address
Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer