Re: distinguish between null variable and unset variable
| From: | Lars Torben Wilson | Date: | Thu, 22 Jan 2009 04:57:57 +0000 |
| Subject: | Re: distinguish between null variable and unset variable | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-286987@lists.php.net to get a copy of this message | ||
2009/1/21 Daniel Brown <danbrown@php.net>:
> On Wed, Jan 21, 2009 at 20:27, Jack Bates <ms419@freezone.co.uk> wrote:
>> How can I tell the difference between a variable whose value is null and
>> a variable which is not set?
>
> Unfortunately, in PHP - like other languages - you can't.
>
> A variable is considered to be null if:
> * it has been assigned the constant NULL.
> * it has not been set to any value yet.
> * it has been unset().
Actually, you can, but it's not terribly pretty. Check for the
variable name as a key in the array returned from get_defined_vars():
<?php
$foo = 0;
$bar = null;
$variables = get_defined_vars();
// Check for $foo, $bar, and $baz:
foreach (array('foo', 'bar', 'baz') as $var) {
if (!array_key_exists($var, $variables)) {
echo "\$$var does not exist in the current scope.\n";
continue;
}
if (is_null($$var)) {
echo "\$$var exists and is null in the current scope.\n";
continue;
}
echo "\$$var exists and is not null in the current scope.\n";
}
?>
Again, not that pretty, and it only checks the local scope, but it can be done.
Regards,
Torben