php

How to check if a variable is NULL in PHP?

NULL stands for a variable without value. To check if a variable is NULL you can either use is_null($var) or the comparison (===) with NULL. Both ways, however, generate a warning if the variable is not defined. Similar to isset($var) and empty($var), which can be used as functions. isset($var) returns true(boolean) if the passed variable is defined and contains a value unequal to NULL. empty($var) returns true(boolean), if the passed variable is not defined or contains an empty value. Here “empty” is defined in a very general way and also includes 0(integer), false(boolean), or the empty string.
 

Example : is_null($var), isset($var) and ($var === null)
<?php
    $var = null;
 
    echo('$var with the value NULL:' . "\n\n");
     
    var_dump(is_null($var)); // true
    var_dump($var === null); // true
    var_dump(!isset($var)); // true
    var_dump(empty($var)); // true
 
     
    echo("\n\n");
    echo('undefined variable $var2:' . "\n\n");
 
    var_dump(is_null($var2)); // true
    var_dump($var2 === null); // true
    var_dump(!isset($var2)); // true
    var_dump(empty($var2)); // true
?>

Output:

$var with the value NULL:

bool(true)
bool(true)
bool(true)
bool(true)


undefined variable $var2:

Notice:  Undefined variable: var2 in [...][...] on line 15
bool(true)

Notice:  Undefined variable: var2 in [...][...] on line 16
bool(true)
bool(true)
bool(true)
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More
Comparison of the results: is_null(), ===, isset() and empty()

The following table shows the differences between is_null(), ===, isset() and empty():

NULL
false (Boolean)
0 (Integer)
0.0 (Float)
"" (String)
"0" (String)
is_null($var) true false false false false false
($var === null) true false false false false false
isset($var) false true true true true true
empty($var) true true true true true true
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *