0

Possible Duplicate:
Is !$page == false or $page in php?

What is the difference between these two types of checks? And which would be the correct way of type checking called functions or methods that fail and return false?

if (!is_dir($path)) {...}

or

if (is_dir($path) === false) {...}
Community
  • 1
  • 1
JoelM
  • 9
  • 1

4 Answers4

2
(!is_dir($path)){...}

IF is_dir($path) is EQUAL to false.

(is_dir($path) === false){...}

IF is_dir($path) is IDENTIFCAL to false. This is more explicit in the sense that the result of is_dir($path) MUST be a boolean FALSE value. Nothing else will do.

Run this example:

<?php

$var = 0;

if($var == false){
    echo 'Var is EQUAL to FALSE.';
}

if($var === false){
    echo 'Var is IDENTICAL to FALSE.';
}

?>

Read up on the comparison operators here.

Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

!$a will be true if $a is set to 0, or if $a is unset. The triple equal sign strictly checks for false, not just for null-ish values.

Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66
0

the === operator is the "same value and same type" comparison. So $foo === false is only true if $foo is already a bool type equal to false, whereas !$foo will perform different operations depending on the type of $foo (for example, if $foo is an object or resource, then it will check if it's a null value. If it's a string then it checks for null (and I think an empty string too, but I'm uncertain on that). If it's an integer then it checks if it's zero or not. Basically it works similar to C's ! operator before they added the bool type (where boolean values were really int values).

In your code, both examples are "correct" although the first example, using the ! operator, is the most succinct and should be preferred.

Dai
  • 141,631
  • 28
  • 261
  • 374
0

I think it will be easier to understand by giving some examples(you need to execute php commands in command prompt/ terminal) ! is logical operator not and it is defined by php documentation as "!$a has Result TRUE if $a is not TRUE."

php -r "$a=NULL; $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a=''; $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a=array(); $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a=false; $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a=0; $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a=0.0; $b = !$a; var_dump($b);"

returns bool(true)

php -r "$a='0'; $b = !$a; var_dump($b);"

returns bool(true)

While $a === false will be true only if $a is actuall bollean and its value is false(all other previvious examples will be false with ! operator)

php -r "$a=false; $b = $a === false; var_dump($b);"

returns bool(true)

In your example just use not operator ! because you dont need to check type of is_dir result.

Igor
  • 1,835
  • 17
  • 15