Search code examples
phpboolean-logicnegationboolean-algebra

Logical Boolean Negation Operator Precedence and Association


here's my first question(s) on StackOverflow, and as such I imagine it has been asked here before, but everything I type into the search bar gives me different questions. (Or sometimes "no" results at all!)

I am learning on w3Schools, but I saw this seemingly simple code snippet which stirred up a small parcel of questions:

In essence the code says:

if(! test === FALSE)
  display("test successful!");
else
  display("test failed...")

"test" in this particular case returns a string on success or a (Boolean) FALSE upon failure.

Here are the questions that stirred within me.

  1. As for the exclamation point (aka "Logical NOT" aka "Negation Operator") at the beginning of a conditional/if statement, is that:

    A) Applied to the whole statement within the parentheses?, or

    B) Only associated to "test"?

Note: The negation operator's associativity may not change the outcome in this instance, but its associativity would matter in a case like: (! FALSE || TRUE), yeah?

  1. I understand how the Negation Operator works on Booleans, but how does the Negation Operator behave when faced with a (PHP) string?

    A) Does the negation operator's behavior change if the string happens to be something tricky like "true" or "0"?

  2. Is (! test === FALSE) the same as (test !== FALSE)? Why didn't they just use "!=="?

HERE is the actual code in question:

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}

Further PHP question: Is there some sort of advantage to use filter_var() over filter_input() in this circumstance? Why did w3Schools use filter_var() and not filter_input()?


Solution

    1. As you can see in the doc operators in PHP have different priorities. It means:! applied to $test first.

    2. According to the doc, empty string '' or '0' will be converted to false, otherwise true.

    3. It is not the same. When $test equals to empty string '' or '0' this two conditions have different behavior.