PHP is_null() Function: How to Check If Variable is NULL

PHP is_null() function is “used to find whether a variable is NULL or not.” A unique NULL value represents the variable with no value.

The variable is considered to be NULL if:

  1. If it has been explicitly set to the NULL value.
  2. It has not been set to any value yet.
  3. It has been unset().

Syntax

is_null( mixed $var )

Parameters

$var(required): It is the variable being evaluated.

Return value

It returns TRUE when $var will be NULL; otherwise, it returns FALSE.

Visual Representation Visual Representation of PHP is_null() FunctionExample 1: How to Use is_null() Function

<?php

 $var = NULL;
 $var2 = "NULL";
 $var3 = 0;
 $var4 = "";
 
 if(is_null($var)) {
 echo 'The variable is NULL'."\n";
 }
 else {
 echo 'The variable is not NULL'."\n";
 }
 
 if(is_null($var2)) {
 echo 'The variable is NULL'."\n";
 }
 else {
 echo 'The variable is not NULL.'."\n";
 }
 
 if(is_null($var3)) {
 echo 'The variable is NULL'."\n";
 }
 else {
 echo 'The variable is not NULL'."\n";
 }

if(is_null($var4)) {
 echo 'The variable is NULL'."\n";
 }
 else {
 echo 'The variable is not NULL'."\n";
 }

Output

The variable is NULL
The variable is not NULL.
The variable is not NULL
The variable is not NULL

You can use the null or NULL, which is case insensitive, so the output will be the same.

Example 2: Casting to NULL

An empty array is converted to null by non-strict equal ‘==’ comparison. Use is_null() or ‘===’ if it is possible to get an empty array.

<?php

 $a = array();

 if($a == null) {
   echo 'First NULL';
 }
 if($a === null) {
   echo 'Second NULL';
 }
 if(is_null($a)) {
   echo 'Third NULL';
 }

Output

First NULL

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.