简体   繁体   中英

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
}

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM