Domanda

What is the difference, specifically in PHP? Logically they're the same (or so seem), but is there any advantage with one over the other? Including micro-benchmarking if any difference.

Example code:

$a = fc();

// Example 1
if (!$a) echo "Ex. 1";

// Example 2
if (false === $a) echo "Ex. 2";

// Example 3
if (true !== $a) echo "Ex. 3";

function fc()
{
    return false;
}
È stato utile?

Soluzione

!

Just invert your result value (boolean or not) from true to false or false to true

Example:

if (!file_exists('/path/file.jpg')) {
    // if file NOT exists
}

=== false (or true)

The value compared MUST BE a boolean false or true.

Example:

$name = 'Patrick Maciel';

if ($name === true) {
  // not is, because "Patrick Maciel" is a String
}

BUT if you do that

if ($name == true) {
  // it is! Because $name is not null 
  // and the value is not 'false': $name = false;
}

In this case, this operator is just for check that:

$connection = $this->database_connection_up();
if ($connection === true) {
  echo 'connected to database';
} else {
  echo 'error in connection';
}

$valid_credit_card = $this->validate_credit_card($information);
if ($valid_credit_card === false) {
  echo 'Your credit card information is invalid'
}

!== true (or false)

It's the same thing. Only the opposite of ===, ie: the value cannot be a boolean true or false.


Sorry for my english.

Altri suggerimenti

The difference boils down to type juggling. The ! operator converts a value to its boolean value, then inverts that value. === false simply checks if the value is, in fact, false. If it's not false, the comparison will be false.

If the value being compared is guaranteed to be a boolean, these operations will behave identically. If the value being compared could be a non-boolean, the operations are very much different. Compare:

php > $a="0";
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(false)
php > $a = false;
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(true)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top