I need to differenciate a completely undefined variable from a defined variable containing null. Here is what I tried so far :
$v1 = null;
$variables = get_defined_vars();
echo (isset($v1) ? '$v1 set' : '$v1 not set') . PHP_EOL;
echo (is_null($v1) ? '$v1 null' : '$v1 not null') . PHP_EOL;
echo (empty($v1) ? '$v1 empty' : '$v1 not empty') . PHP_EOL;
echo (isset($variables['v1']) ? '$v1 defined' : '$v1 not defined') . PHP_EOL;
echo PHP_EOL;
echo (isset($v2) ? '$v2 set' : '$v2 not set') . PHP_EOL;
echo (is_null($v2) ? '$v2 null' : '$v2 not null') . PHP_EOL;
echo (empty($v2) ? '$v2 empty' : '$v2 not empty') . PHP_EOL;
echo (isset($variables['v2']) ? '$v2 defined' : '$v2 not defined') . PHP_EOL;
This outputs :
$v1 not set
$v1 null
$v1 empty
$v1 not defined
$v2 not set
$v2 null
$v2 empty
$v2 not defined
You may run this example here
I get the exact same results with both variables, but PHP emits a notice about calling is_null
on the undefined $v2
variable. So PHP does indeed make a difference between undefined and null. What test could I run on the variables to see this difference ?
UPDATE 1 : based on this question, the only way to do this is to detect the notice PHP emits, which is extremly dirty.
UPDATE 2 : Actually, it can be done, I was using get_defined_vars()
wrong, somehow
$v1 = null;
echo (array_key_exists('v1', get_defined_vars()) ? '$v1 defined' : '$v1 not defined') . PHP_EOL;
echo (array_key_exists('v2', get_defined_vars()) ? '$v2 defined' : '$v2 not defined') . PHP_EOL;
This outputs :
$v1 defined
$v2 not defined
Thank you Iłya Bursov from pointing this out