0

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
}
7
  • Have you tried it? What are your own conclusions? Do you have any specific reason for your suspicions? Commented Feb 12, 2014 at 15:23
  • 1
    Yes, they are. Look at the php comparision table: php.net/manual/en/types.comparisons.php Commented Feb 12, 2014 at 15:23
  • I have, the above statement seems to evaluate to true regardless if the var is NULL or not. Seems to me it shouldnt be this way Commented Feb 12, 2014 at 15:24
  • There is a difference though. The last one doesnt use a function, which might have influence on the memory used. But not in an amount you should care about Commented Feb 12, 2014 at 15:26
  • Might depend on the way it's used. Even though you didn't add a mysql tag, are you using this for DB, or just PHP? Commented Feb 12, 2014 at 15:29

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.