PHP is_null() and ==null

PhpNull

Php Problem Overview


In PHP, what is the difference between is_null and ==null in PHP? What are the qualifications for both to return true?

Php Solutions


Solution 1 - Php

is_null is the same as === null. Both return true when a variable is null (or unset).

Note that I'm using === and not ==. === compares type as well as value.

Solution 2 - Php

So you can understand it better:

$a = null;
$b = 0;

is_null($a) // TRUE
$a == null  // TRUE
$a === null // TRUE
is_null($b) // FALSE
$b == null  // TRUE
$b === null // FALSE

Solution 3 - Php

There are a couple really good charts on the php.net site that show how different values react:

Type Comparison - php.net

Solution 4 - Php

You can check the comparison between is_null() and null === $var

Good comparison between two

Solution 5 - Php

===null is recommended by Rasmus Lerdorf, the inventor of PHP. Rasmus says the test for null is faster than the test of isset. His recommendation is sufficient reason to look at the difference seriously. The difference would be significant if you had a small loop going through the same code thousands of times in the one Web page request.

UPD: Some speed test for is_null and strict comparison:

PHP 5.5.9
is_null - float(2.2381200790405)
===     - float(1.0024659633636)

PHP 7.0.0-dev
is_null - float(1.4121870994568)
===     - float(1.4577329158783)

Solution 6 - Php

== doesn't check the type, so somehow, somewhere, something like the string '' or the string 'null' may come up as equal to null.

Use triple equals sign, ===, to not only check two values are equal but also that they are of the same type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkel_ff0080View Question on Stackoverflow
Solution 1 - PhpRocket HazmatView Answer on Stackoverflow
Solution 2 - PhpDaniel RibeiroView Answer on Stackoverflow
Solution 3 - PhpkeithhatfieldView Answer on Stackoverflow
Solution 4 - PhpUmut KIRGÖZView Answer on Stackoverflow
Solution 5 - PhpAchim KraußView Answer on Stackoverflow
Solution 6 - PhpDanReduxView Answer on Stackoverflow