PHP is_null() and ==null
PhpNullPhp 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:
Solution 4 - Php
You can check the comparison between is_null() and null === $var
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.