Reputation: 113956
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
?
Upvotes: 29
Views: 68434
Reputation: 111
As of php 7.2 directly setting a variable is depreciated. You should not use it in this fashion you should look into using unset instead. https://www.php.net/manual/en/language.types.null.php
unset($v);
will result in the same false when checking to see if the variable is null or unset.
isset($v) === false
is_null($v) === false
Upvotes: 0
Reputation: 43619
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 and/or local namespace, you use the
unset($var);
This will make $var
not set at all. You won't be able to find in $GLOBALS
.
Upvotes: 23
Reputation: 546035
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)
Upvotes: 26
Reputation: 38308
Also, you can set the variable to null
:
<?php
$v= 'string';
var_dump(isset($v));
$v= null;
var_dump(isset($v));
?>
Upvotes: 2