The unset function in PHP
The unset() function is used to clear or destroy the value of a given variable.
To check variable is set or not (assigned a value or not) see PHP isset chapter.
How to use the unset function?
Following is the general syntax of using the PHP unset function:
Example of unset() function
The following example shows how to use the unset function to destroy the value of a variable.
$var1 = 1;
//unset the variable
Notice: Undefined variable: var1 in F:xampphtdocstest.php on line 7
The above program will return a notice in the second call as $var1 is unset.
Uses of unset() function
The unset PHP function can be used to clear session variable values, for example, in a scenario where shopping cart items are stored in the session variables. As a user has completed a transaction, you may want to clear session variables carrying products while still maintaining the user’s id etc.
Scope of unset
The behavior of unsetting a variable in PHP can be different scope wise. For example, if you are destroying a global variable by using the unset() function, it will destroy it only locally.
If a variable is destroyed inside a function, it will be unset only in the context of the rest of the function. The variable will retain the value in other calls.
Further reading: using unset in session variables.