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.
The problem you're having is that NULL isn't anything - it's the absence of a value.
When you try to
echo
orprint
it, you get the notice about an Undefined Variable because the value of$name
is not set to anything, and you can'techo
the absence of something.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:
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:
This outputs
string(4)"test"
- a string containing test, which had a length of 4