What is the difference between these methods and how to check for NULL correctly?

All three methods are null checking,

if($sth == NULL) if($sth === NULL) if(is_null($sth)) 

which way is right?

+4
source share
3 answers

They check three different things:

 if ($sth == NULL) 

This checks if $sth is equal to null . This means that this will pass if $sth is actually 0 .

 if ($sth === NULL) 

This checks if $sth is null .

 if (is_null($sth)) 

This checks to see if $sth null type (others check the value of $sth ).

The methods === and is_null will always give the same answer; == sometimes gives a different answer.

+11
source

Only the first tests, if $sth is NULL, the value 0 will also be true. The second checks if the type is equal. Thus, the NULL value as the value for $sth will be true. The third will only work with variables, not function results.

Also a little hint: from time to time it occurs to me that I am mistaken if($sth == NULL) to if($sth = NULL) , which will make it difficult to find errors. Better enter if(NULL == $sth) , where you get an interpreter error when you write incorrectly, which will point you in the right direction.

+1
source

I would use

 if(is_null($sth)) 

but I think it’s good

0
source

All Articles