Example #5 Correctly checking the result of validation
<?php
$value = '0';
// Wrong: 0 is a valid integer, but it is falsy
if (!filter_var($value, FILTER_VALIDATE_INT)) {
echo "Wrong check: '$value' rejected\n";
}
// Correct: compare strictly against false
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
echo "'$value' is not a valid integer\n";
} else {
echo "'$value' is a valid integer\n";
}
?>
The above example will output:
Wrong check: '0' rejected
'0' is a valid integer
Example #6 Checking the result of boolean validation
<?php
foreach (['yes', 'no', 'maybe'] as $value) {
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// false is a valid result here, so check for null instead
if ($result === null) {
echo "'$value' is not a valid boolean\n";
} else {
echo "'$value' is ", var_export($result, true), "\n";
}
}
?>
The above example will output:
'yes' is true
'no' is false
'maybe' is not a valid boolean
See Also
filter_var_array() - Gets multiple variables and optionally filters them
filter_input() - Gets a specific external variable by name and optionally filters it