Search code examples
phpnulloutputechovar-dump

Why the 'NULL' value of a variable is not displayed using echo and print but displayed with var_dump() function?


As we all know if a variable is created without a value, it is automatically assigned a value of NULL.

I have following code snippets :

<?php
    $name;
    echo $name;     
?>

AND

<?php
    $name;
    print $name;     
?>

Both of the above code snippets' output is as below(it's exactly the same) :

Notice: Undefined variable: name in C:\xampp\htdocs\php_playground\demo.php on line 7

I have another code snippet :

<?php
    $name;
    var_dump($name);     
?>

The output of above(last) code snippet is as below :

Notice: Undefined variable: name in C:\xampp\htdocs\php_playground\demo.php on line 8
NULL

So, my question is why the value "NULL" is not getting displayed when I tried to show it using echo and print?

However, the "NULL" value gets displayed when I tried to show it using var_dump() function.

Why this is happening?

What's behind this behavior?

Thank You.


Solution

  • The problem you're having is that NULL isn't anything - it's the absence of a value.

    When you try to echo or print it, you get the notice about an Undefined Variable because the value of $name is not set to anything, and you can't echo the absence of something.

    $name;
    var_dump($name);
    

    The output of this will be NULL to tell you that the variable had no value. It's not a string with the value of "NULL", it's just NULL, nothing, the absence of something.

    Compare this to the following:

    $name = '';
    var_dump($name);
    

    This outputs string(0)"" - this is telling you that $name DID have a value, which was a string which contained no characters ("") totalling a length of 0.

    Finally, look at the following:

    $name = 'test';
    var_dump($name);
    

    This outputs string(4)"test" - a string containing test, which had a length of 4