tags:

views:

258

answers:

6
<?php
    $var = NULL;

    var_dump(isset($var)); // bool(false)
    var_dump(isset($unset_var)); // bool(false)
?>

isset($var) should return TRUE, since it has been set to NULL.

Is there any way to check for this?

Thanks!

+1  A: 

Not very pretty, but...

array_key_exists('var', $GLOBALS);

(You can't use @is_null($var), because it evaluates to true either way [and it's not really good practice to suppress errors using the @ operator...])

Ant P.
Not really. is_null() returns true for undefined variables.
chaos
Yeah, noticed that after I posted. Fixed it now.
Ant P.
A: 

Any unset var will evaluate to null:

php > $a = null;
php > var_dump($a === null);
bool(true)
php > var_dump($a === $b);
bool(true)

(using interactive console - php -a )

benlumley
A: 

if it's in global scope, you can try checking if the key exists in the $GLOBALS superglobal (using array_key_exists()).

but you're probably doing something wrong if you need to know this :)

Cal
$GLOBALS, not $_GLOBALS.
chaos
A: 

Aren't variables initialized to NULL by default? So, there isn't really a difference between one that hasn't been inited and one that you've set to NULL.

twk
The difference is an entry in whatever namespace it exists in.
chaos
Yes, but what effect does that have on someone writing a script? Do you have to handle the 2 cases differently?
twk
Its an entry with no value (NULL is a value that means NO VALUE) - something IS null, it is not SET to null. Entries in a namespace bare no meaning on detection of the initialization of a variable that has no value associated with it.
Syntax
Again I ask, "Do you have to handle the 2 cases differently?" I want to be clear if we are talking about functionality as experienced by the script writer or something else.
twk
You would have to handle them separately. is_null for null value checking and isset to see if the variable has been initiated.
Syntax
+1  A: 

If it's a global, you can do:

if(array_key_exists('var', $GLOBALS))
chaos
+7  A: 

use get_defined_vars() to get an array of the variables defined in the current scope and then test against it with array_key_exists();

Edited:

if you wanted a function to test existence you would create one like so:

function varDefined($name,$scope) {
  return array_key_exists($name, $scope);
}

and use like so in any given scope:

$exists = varDefined('foo',get_defined_vars());

Should work for any scope.

Mainegreen
That's what I figured is the only way, since this is what happens in PHP: var_dump($random_nonexistent_var); // NULLThanks!
Infinity