14

Possible Duplicate:
php == vs === operator

i have the following code fragment and it doesn't make sense to me why would NULL be evaluated in 3 different ways. Consider the variable $uploaded_filenames_array as UNKNOWN - we don't know whether it's still an array or a NULL. That's what we are trying to check.

//-----------------------------------------------
if (is_null($uploaded_filenames_array)){
    echo "is_null";
}
else{
    echo "is_NOT_null";
}
//-----------------------------------------------
if ($uploaded_filenames_array == NULL){
    echo "NULL stuff";
}
else{
    echo "not NULL stuff";
}
//-----------------------------------------------
if ($uploaded_filenames_array === NULL){
    echo "NULL identity";
}
else{
    echo "not NULL identity";
}
//-----------------------------------------------

i am getting the following response:

is_NOT_null 
NULL stuff 
not NULL identity 

can somebody help to understand what is the programmatic difference between these 3 ways of checking NULL?

Community
  • 1
  • 1
Rakib
  • 12,376
  • 16
  • 77
  • 113
  • is_null is equivalent to "===". – Tarun Aug 28 '12 at 09:37
  • 2
    how is this question an exact duplicate of http://stackoverflow.com/questions/589549/php-vs-operator? That question doesn't talk about is_null. – Rakib Aug 28 '12 at 09:54

4 Answers4

20

is_null($a) is same as $a === null.

($a === null is bit faster than is_null($a) for saving one function call, but it doesn't matter, just choose the style you like.)

For the difference of === and ==, read PHP type comparison tables

$a === null be true only if $a is null.

But for ==, the below also returns true.

null == false
null == 0
null == array()
null == ""
xdazz
  • 158,678
  • 38
  • 247
  • 274
3

You should read this http://php.net/manual/en/language.operators.comparison.php. Also no need to use is_null function to check only on NULL. === is faster...

Joaquin Marcher
  • 336
  • 5
  • 14
Igor Timoshenko
  • 1,001
  • 3
  • 14
  • 27
1

== checks if the value is equal e.g.:

>> "123" == 123
<< true

=== checks if the value & type are equal e.g.:

>> "123" === 123
<< false
Ivan
  • 34,531
  • 8
  • 55
  • 100
Genosite
  • 359
  • 1
  • 8
1

The === operator tests for the same value and the same TYPE. An empty string might evaluate to null, but it is not of the null type - hence this fails.

The == operator basically checks to see if they are pretty much the same - by that, do the evaluate to the same value. Being empty, this will evaluate to null, hence this fails.

The is_null function does a fairly thorough check - much more like the === operator.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80