How to delete a variable in PHP
There are three ways to delete defined variables in PHP:
- unset($var)
- $var = (unset)$var
- $var = null
Only the first of these ways actually deletes the variable completely. The other two, set it to NULL, which means that the variable no longer has a value, but in principle still exists. Accessing this would not generate the error “variable does not exist”.
Example: “unset($var)” vs “(unset)$var” vs “$var = null”
In this example the variables $var1, $var2 and $var3 are defined identically.
[st_adsense]
<?php // Defining sample variables $var1 = 'variable 1'; $var2 = 'variable 2'; $var3 = 'variable 3'; // Output the three variables before deleting var_dump($var1, $var2, $var3); // Delete variables unset($var1); $var2 = (unset)$var2; $var3 = null; // Output variables after deleting // var1 should get an error because it was completely deleted var_dump($var1, $var2, $var3); // List all currently available variables var_dump(get_defined_vars()); ?>
Output:
string(10) "variable 1" string(10) "variable 2" string(10) "variable 3" Notice: Undefined variable: var1 in [...][...] on line 17 NULL NULL NULL array(6) { ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array(0) { } ["_FILES"]=> array(0) { } ["var2"]=> NULL ["var3"]=> NULL }[st_adsense]