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
?
To set the value of a variable is it's equal to null , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined , otherwise it returns the left-hand side operand.
The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.
PHP considers null is equal to zero.
is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .
Use unset($var);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With