Jump to content

Why is this expression used in the tutorial?


Recommended Posts

In the lesson on PHP Filters in the code sample "Validate an Integer" there is the following code:

<?php
$int = 100;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
    echo("Integer is valid");
} else {
    echo("Integer is not valid");
}
?> 

Why use this expression:

(!filter_var($int, FILTER_VALIDATE_INT) === false)

instead of what seems to me to be the more logical expression?:

  (filter_var($int, FILTER_VALIDATE_INT) === true)

Thanks.

Link to post
Share on other sites

filter_var() with the FILTER_VALIDATE_INT filter returns an integer, not true, so === true will always fail. By using The ! operator, they transform it into a boolean. This boolean, for any integer other than zero, is always false. This solution doesn't account for the integer zero which converts to true, but W3Schools also has a section talking about that.

They could just use !!filter_var() or (bool)filter_var() and they wouldn't need the === false part. This would still not solve the integer zero problem, though.

  • Like 1
Link to post
Share on other sites
  • 1 year later...
On 10/11/2019 at 2:04 AM, Ingolme said:

They could just use !!filter_var() or (bool)filter_var() and they wouldn't need the === false part. This would still not solve the integer zero problem, though.

I think the correct way is to do the check is this way :

if (!(filter_var($int, FILTER_VALIDATE_INT) === false)) {
  echo("Integer is valid");
} else {
  echo("Integer is not valid");
}

Because the rule is that `filter_var' return bool(false) only if there is an invalid integer, else return int(the value). And we test "!(fnc === false)" because the `!`operator take precedence over `===` otherwise.

More over hese is no integer zero problem anymore ;)

==> What do you think of that ?

Edited by Nicos99
Link to post
Share on other sites
  • Funce locked this topic
Guest
This topic is now closed to further replies.
×
×
  • Create New...