Jump to content
Sign in to follow this  
majuk

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.

Share this post


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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...