I'm using filter_input now and I want it to return true on every number (0-9) and false on non-numbers (a-z, A-Z etc..)
Now, I use this script (just an example script but the idea is the same):
<?php
$i = filter_input(INPUT_GET, 'i', FILTER_SANITIZE_NUMBER_INT);
if ($i)
{
echo 'good';
}
else
{
echo 'bad';
}
If I use 1-9 as GET variable (so like test.php?i=1
), it shows good
.
If I use a-Z as GET variable (so like test.php?i=a
), it shows bad
. So far so good.
But if I use 0 as GET variable, it shows bad as well. The variable can be 0 and should be true when the GET variable is 0.
Can anybody explain me why 0 returns false? I mean the GET variable is set and 0 is a number. Is it just because 0 is a falsey value?
0
is a falsey value in PHP. if (0)
is false
.
Further, you're using the sanitisation filter, which will basically never fail. You want to use FILTER_VALIDATE_INT
to validate whether the input is an integer.
Further, filter_input
returns either false
, null
or 0
here. They're all equally falsey, meaning == false
. You need to explicitly distinguish between them:
$i = filter_input(INPUT_GET, 'i', FILTER_VALIDATE_INT);
if ($i === null) {
echo 'value not provided';
} else if ($i === false) {
echo 'invalid value';
} else {
echo 'good';
}