Kisaragi
Kisaragi

Reputation: 2218

PHP checking for NULL value

Just out of curiosity (and a bit of necessity):

if(! is_null($var)){
     //do something
}

Is the above statement the same as

if($var != NULL){
//do something
}

Upvotes: 0

Views: 80

Answers (3)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

No they are not the same.

The is_null function compairs the type also.

Example:

var_dump(is_null(0)); // bool(false) 
var_dump(0 == NULL);  // bool(true) 
var_dump(0 === NULL); // bool(false)

So in your case

if(! is_null($var)){
     //do something
}

Would be the same as

if($var !== NULL){
    //do something
}

Upvotes: 4

Tsueah
Tsueah

Reputation: 263

I'm not sure what exactly you're testing, but on:

a) $var = NULL; neither of the statements triggers,

b) $var = 0; is_null triggers and

c) $var = ''; is_null triggers aswell.

So the statements above are definitely not coming to the same conclusion.

See for yourself:

echo 'testing NULL case<br>';
$var = NULL;
if(! is_null($var)){
    echo 'var is_null<br>';
}
if($var != NULL){
    echo 'var != null<br>';
}

echo 'testing 0 case<br>';
$var = 0;
if(! is_null($var)){
    echo 'var is_null<br>';
}
if($var != NULL){
    echo 'var != null<br>';
}

echo 'testing empty string case<br>';
$var = '';
if(! is_null($var)){
    echo 'var is_null<br>';
}
if($var != NULL){
    echo 'var != null<br>';
}

this outputs

testing NULL case
testing 0 case
var is_null
testing empty string case
var is_null

Upvotes: 1

Jesper
Jesper

Reputation: 599

Yes this is (almost) correct, you can test this yourself:

    $emptyvar1 = null;
    $emptyvar2="";
    if(is_null($emptyvar1) && $emptyvar1 == NULL){
        echo "1";
    }
    if(is_null($emptyvar2)){
        echo "2";
    }
    if($emptyvar2 == null){
        echo "3";
    }
    if($emptyvar2 === null){
        echo "4";
    }

This will print 1 and 3. because an empty string is equal to null if you only use 2 times = if you use 3 times = it aint.

=== also checks object type == only checks value

Upvotes: 1

Related Questions