I have this chunk of code:
$range = array (
'options' => array (
'min_range' => 0,
'max_range' => 10
)
);
if (!$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range)) {
exit ('Error');
}
The "number" input will be sent from a with options from 0 to 10.
the problem is that if number = 0 this returns "Error".
What's wrong with that?
Thanks
This is because !0
is true. Why? By adding the !
you are doing a boolean check, so your variable gets converted. And according to the manual:
When converting to boolean, the following values are considered
FALSE
:
the boolean
FALSE
itselfthe integer
0
(zero)the float
0.0
(zero)the empty string, and the string
"0"
...
So the integer 0
gets converted to false
while all other integers are converted to true
.
This is why you need to do a type safe check for false
or null
as these are the values filter_input()
returns if it fails for some reason.
$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range);
if ($number === false) {
//filter failed
}
if ($number === null) {
//variable was not set
}
I found the solution!
if (
!$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range) === 0
|| !filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range) === FALSE)
{
exit ('Error');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With