majuk Posted October 9, 2019 Share Posted October 9, 2019 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 comment Share on other sites More sharing options...
Ingolme Posted October 11, 2019 Share Posted October 11, 2019 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. 1 Link to comment Share on other sites More sharing options...
Nicos99 Posted November 18, 2020 Share Posted November 18, 2020 (edited) 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 November 18, 2020 by Nicos99 1 Link to comment Share on other sites More sharing options...
Funce Posted November 19, 2020 Share Posted November 19, 2020 Please do not reply to old topics. Link to comment Share on other sites More sharing options...
Recommended Posts