NULL in PHP How to set and check NULL variables?

PHP NULL value and NULL variables: Here, we will find out about the NULL in PHP, we will likewise figure out how to set a variable with NULL, how to unset a variable and how to check whether a variable is NULL or not?

Invalid in PHP

The invalid is a unique value in PHP, it speaks to that a variable contains any value or a variable is vague. Unclear variable or variable with no value is a kind of invalid.

On the off chance that a variable is doled out with a NULL value, or if any variable isn’t appointed any value or if a variable is disconnected utilizing disconnected() work – variable will be considered as invalid 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() work, it returns genuine (1), if a variable contains a NULL value or if a variable is indistinct.

Note: If the variable doesn’t have any value or disconnected utilizing by unset() work, PHP restores a notification that “Vague variable”

Example:

    Input:
    $var = NULL;

    Function call:
    is_null($var);

    Output:
    1

PHP code to exhibit utilization 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

Leave a Comment

error: Alert: Content is protected!!