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
?
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
?
Also, you can set the variable to null
:
<?php
$v= 'string';
var_dump(isset($v));
$v= null;
var_dump(isset($v));
?>
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)
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
.