What is the difference between a variable which is set to NULL and a variable that is not set?
Take a look at PHP types comparison table #1 (Comparisons of $x
with PHP functions). The lines #2-#4 read:
| Expression | gettype() | empty() | is_null() | isset() | if($x) |
|-----------------+-----------+---------+-----------+---------+--------|
| $x = null; | NULL | TRUE | TRUE | FALSE | FALSE |
| var $x; | NULL | TRUE | TRUE | FALSE | FALSE |
| $x is undefined | NULL | TRUE | TRUE | FALSE | FALSE |
Can you spot any difference between them? Me neither.
There is one difference, though. When a variable $x
is undefined, gettype($x)
, is_null()
, if($x)
and any code that attempts to get its value triggers a notice ("Notice: Undefined variable: x"). empty()
and isset()
do not trigger any error, warning or notice when their argument does not exist because their purpose is to classify the presence and value of their argument.
How would I then be able to distinguish between a variable whose value is NULL
and a variable which does not exist?
Apart from the notice triggered as explained above, there is no difference between a variable whose value is NULL
and a variable that doesn't exist. Even the notice is just a hint about a possible error in the code or a way to improve its readability but with or without it, the behaviour is the same.
I cannot figure out any practical usage of telling apart an undefined variable from a variable that stores NULL
.
What makes a variable exist PHP?
A variable exist in PHP since it was assigned a value for the first time until it is unset()
or until the code exits its scope (whichever comes first).