is_null vs null in php

is_null vs null in php
is_null vs null in php

Before we go into details of is_null vs null in php. Let’s see common debate-

Junior Developer (To Senior) : Sir, I am getting this value as null. I think I must use === null to check the value.
Senior : No, use is_null() function
Junior Developer : But why? we can directly use this way to compare variable with null.
Senior : See, PHP has provided its inbuilt function to check if the value is null OR not then why are you arguing on === null. It’s always good to use inbuilt function.
Junior Develop: But Sir?
Senior : See, I don’t want any argument on this. Do what I say.
Junior Developer: Okay, sir.

What is is_null() in PHP ?

As per the php.net site documentation, is_null() function finds whether provided variable is NULL.

Actually, is_null() function works similar like isset() but as its opposite. So it returns TRUE in all the cases except when there is no value assigned to a variable OR assigned as NULL.

Following table will clearly show how isset() is opposite to is_null().

Variable $v is_null($v) isset($v)
“” bool(FALSE) bool(TRUE)
null bool(TRUE) bool(FALSE)
var $v; bool(TRUE) bool(FALSE)
$v is undefined bool(TRUE) bool(FALSE)
array() bool(FALSE) bool(TRUE)
array(‘x’) bool(FALSE) bool(TRUE)
FALSE bool(FALSE) bool(TRUE)
TRUE bool(FALSE) bool(TRUE)
1 bool(FALSE) bool(TRUE)
0 bool(FALSE) bool(TRUE)
“1” bool(FALSE) bool(TRUE)
“php” bool(FALSE) bool(TRUE)

Let’s see example in action-

<?php

$var = NULL;

if(is_null($var)) {
    echo 'variable with null value';
} else {
    echo 'variable contains value';
}
// OUTPUT

variable with null value

What is ===NULL?

NULL comes into picture when no value assigned to that variable which means a variable is declared with no value assigned to it.

Similarly, when we return null from the function then it means that there is nothing to return from this function and hence all the related operations are completed within the functions itself.

Here is the small example to understand that when there is no value assigned to a variable then the type of the variable is NULL.

<?php

$var;
var_dump($var);
// OUTPUT

NULL

Now, the main question arises if both of them perform the same operation and has absolutely no difference then what is the exact difference in between them?

is_null vs null in php


is_null() ===NULL
It is marginally slower due to function call overhead It is faster
It checks if the value is of the data type NULL It checks if the value is NULL and data type is also of type NULL

Conclusion:

It is better to use inbuilt is_null function when there is small number of request to the respective request. But as the site grows and number of users actively uses that service. So, in performance point of view it is good to use === NULL to check the value.

So, in is_null vs null in php battle, ===null will win the match because of its fast performance.