Possible problems with logical operators

0

Hello, I would like to know if you have a problem or if it will generate future crashes, use the "!" this way:

if (!(filter_var($email, FILTER_VALIDATE_EMAIL))):
echo "<script>alert('O email digitado: ".$email. " não é válido!');</script>";
echo "<script>window.history.back();</script>"; 
exit;
else:

instead of the way it is on the W3C website:

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

W3C - In this case I only mean using the "!" operator. on the first line and I would also like to know along with "=== false" if you have problems with that difference or not.

    
asked by anonymous 07.03.2017 / 14:54

2 answers

3

There is a difference, but I do not know if it applies exactly to the case presented. The difference between using !(condition) and condition === false is that PHP naturally considers some values, other than false , to be false. Some of them: number zero, empty array, empty string.

$tests = [0, [], "", false];

foreach ($tests as $condition)
{
  if (!$condition)
  {
    echo "A condição é verdadeira!" . PHP_EOL;
  }
}

Running the above test, you will notice that the four tests will pass, since the four values are considered false by PHP and, of course, negating it with ! , the test becomes true. However, when doing:

$tests = [0, [], "", false];

foreach ($tests as $condition)
{
  if ($condition === false)
  {
    echo "A condição é verdadeira!" . PHP_EOL;
  }
}

Only the last test will pass (remembering that the === operator checks if the parameters are identical, while == checks the equality of values).

  Using !(condition) is the same as condition == false , but completely different from condition === false .

For the filter_var function this is important because by reading the documentation, you will see:

Valor retornado: Retorna o dado filtrado, ou FALSE se o filtro falhar.

If somehow the filtered value is considered false by PHP, even if it is valid, its !(condition) condition will indicate the value as invalid while condition === false will only indicate as invalid if the filter actually fails.

/ p>     

07.03.2017 / 15:11
0

The ! ja is basically a === false .

It does the operation for example:

if(!isset($varx)){...

would mean:

If $ varx is not set ...

Or:

If $ varx is exactly the same as false

They have the same effect, not needing to use the 2 together.

And in fact, in the example he is reversing the answer, saying that if the wrong email filter is false it's alright (it's confusing but that's what he's doing)

    
07.03.2017 / 15:02