views:

96

answers:

4

I can use isset($var) to check if the variable is not defined or null. (eg. checking if a session variable has been set before)

But after setting a variable, how do I reset it to the default such that isset($var) returns false?

+6  A: 

Use unset($var);

nacmartin
Does this delete the reference *and* garbage collect the memory also?
Jenko
@Jeremy - yes it does
thephpdeveloper
A: 

Also, you can set the variable to null:

<?php

$v= 'string';
var_dump(isset($v));
$v= null;
var_dump(isset($v));

?>
pygorex1
+5  A: 

As nacmartin said, unset will "undefine" a variable. You could also set the variable to null, however this is how the two approaches differ:

$x = 3; $y = 4;
isset($x);  // true;
isset($y);  // true;

$x = null;
unset($y);
isset($x);  // false
isset($y);  // false

echo $x;  // null
echo $y;  // PHP Notice (y not defined)
nickf
+3  A: 

Further explanation:

While a variable can be null or not null, a variable can also be said to be set or not set.

to set a variable to null, you simply

$var = null;

This will make $var null, equivalent to false, 0 and so on. You will still be able to get the variable from $GLOBALS['var'] since it is still defined/set. However, to remove a variable from the global/local namespace, you use the

unset($var);

This will make $var not set at all. You won't be able to find in $GLOBALS.

thephpdeveloper