5

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

1
  • This is operator precedence: You first assign the result of the function call to $number and then you negate that result converting it to boolean (it could have been boolean, int or NULL). Commented Jun 21, 2014 at 10:58

2 Answers 2

8

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 itself

  • the 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
}
Sign up to request clarification or add additional context in comments.

3 Comments

but what's the difference between 0 and other numbers as they are all in the same range?
@medk Is there something wrong with this answer? Of course you can do both checks in one if() if you are just looking for an unspecific error
this solution also works with filter_var() php.net/manual/en/function.filter-var.php
1

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');
}

1 Comment

You're over-complicating things here. And you're doing the same operation two times albeit you already store the result (at least you tried to, problem with these complicated constructs is that they fail easily) to the variable. @kingkero has some very valid points in his answer, you should try to adopt those. If you want to pull all into the if condition, there is a way to do that, it starts with if (FALSE === ...) {. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.