Re: distinguish between null variable and unset variable

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2009/1/21 Daniel Brown <danbrown@xxxxxxx>:
> On Wed, Jan 21, 2009 at 20:27, Jack Bates <ms419@xxxxxxxxxxxxxx> 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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux