A loose check such as if (!filter_var(...)) rejects both invalid input and a valid false value. Add FILTER_NULL_ON_FAILURE, then compare the result strictly with null so the three outcomes remain distinct.
Last updated: October 25, 2026.
<?php
function parseBoolean(mixed $input): bool
{
$value = filter_var(
$input,
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
);
if ($value === null) {
throw new InvalidArgumentException('Expected a boolean value.');
}
return $value;
}
$enabled = parseBoolean($_POST['enabled'] ?? null);This accepts documented true forms such as true, 1, yes, and on, and false forms such as false, 0, no, off, and an empty string. Other values produce null.
Use a strict three-way check
The PHP validation-filter documentation says FILTER_VALIDATE_BOOLEAN returns true or false for recognized values. With FILTER_NULL_ON_FAILURE, unrecognized values return null. Without that flag, failure also returns false, making it impossible to distinguish invalid text from a valid false value.
The general filter_var() documentation also notes that scalar inputs are converted to strings internally. Use === null for failure, not !$value, == false, or a comparison with the original string.
Separate missing, blank, and false when required
The boolean filter treats an empty string as false. If the field is required, check that the key exists and reject a blank value before calling the parser. This lets the application distinguish “not supplied” from an intentional false selection.
HTML checkboxes require special handling because an unchecked checkbox is normally omitted from form submission. Decide at the form boundary whether absence means false or means missing, and pass an explicit value to the parser. Do not use a direct boolean cast for text input: the PHP boolean conversion rules treat the non-empty string "false" as true. Continue with bounding PHP request input, validating uploaded files, and client-side form validation.