NULL in PHP | How to set and check NULL variables?

By IncludeHelp Last updated : December 11, 2023

NULL in PHP

NULL is a special value in PHP, it represents that a variable does contain any value or a variable is undefined. Undefined variable or variable with no value is a type of null.

If a variable is assigned with a NULL value, or if any variable is not assigned any value or if a variable is unset using unset() function – variable will be considered as null in PHP.

Checking whether a variable contains NULL or not?

To check whether a variable contains a NULL value or not, we use is_null() function, it returns true (1), if a variable contains a NULL value or if a variable is undefined.

Note: If the variable does not has any value or unset using by unset() function, PHP returns a notice that "Undefined variable"

Example

Input:
$var = NULL;

Function call:
is_null($var);

Output:
1

PHP code to demonstrate use of NULL, is_null() and unset()

<?php
    $var1 = "Hello";
    $var2 = NULL;
    $var3 = 10;
    $var4 = 20;
    
    if(is_null($var1))  print("var1 contains NULL\n");
    else print("var1 contains $var1\n");

    if(is_null($var2)) print("var2 contains NULL\n");
    else print("var2 contains $var2\n");

    if(is_null($var3)) print("var3 contains NULL\n");
    else print("var3 contains $var3\n");

    if(is_null($var4)) print("var4 contains NULL\n");
    else print("var4 contains $var4\n");        
    
    //unsetting all variables
    unset($var1);
    unset($var2);
    unset($var3);
    unset($var4);

    if(is_null($var1))  print("var1 contains NULL\n");
    else print("var1 contains $var1\n");

    if(is_null($var2)) print("var2 contains NULL\n");
    else print("var2 contains $var2\n");

    if(is_null($var3)) print("var3 contains NULL\n");
    else print("var3 contains $var3\n");

    if(is_null($var4)) print("var4 contains NULL\n");
    else print("var4 contains $var4\n");            
?>

Output

var1 contains Hello
var2 contains NULL
var3 contains 10
var4 contains 20
PHP Notice:  Undefined variable: var1 in /home/main.php on line 25
var1 contains NULL
PHP Notice:  Undefined variable: var2 in /home/main.php on line 28
var2 contains NULL
PHP Notice:  Undefined variable: var3 in /home/main.php on line 31
var3 contains NULL
PHP Notice:  Undefined variable: var4 in /home/main.php on line 34
var4 contains NULL

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.