User Contributed Notes 48 notes

Since unset() is a language construct, it cannot be passed anything other than a variable. It's sole purpose is to "unset" this variable, ie. to remove it from the current scope and destroy it's associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can't wrap 'unset()' in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass 'scope' to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare 'unset($_GLOBALS[variable])').

I don't know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.

The documentation is not entirely clear when it comes to static variables. It says:

If a static variable is unset() inside of a function, unset() destroys the variable and all its references.

<?phpfunction foo() { static $a;$a++; echo "$a\n"; unset($a);}

foo();foo();foo();?>

The above example would output:

123

And it does! But the variable is NOT deleted, that's why the value keeps on increasing, otherwise the output would be:

111

The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.

Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.

The documentation would be better if it would say:"If a static variable is unset() inside of a function, unset() destroys all references to the variable. "

Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP. I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null. Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):

Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed). If you truly care about the ~4 microseconds saved over <50 variables, more power to you. Otherwise, use unset() to minimize script impact on your system.Note: Tested on PHP 5.3.8 installed via RPM on Fedora 14

The combination of "global" and "unset" in functions can lead to some unexpected results. This is because the "global" function creates a reference to a variable at the time it's executed, so a variable can be deleted out from under a "global $my_variable" declaration in a function. Accessing data that's been deleted with an obsolete reference is usually a bad thing; in some languages it can generate a machine address fault.

function f2() // recreate global variable{ unset($GLOBALS['my_global_var']); // this syntax works with all variable types including arraysglobal $my_global_var; // must do this after unset to access new global variable$my_global_var = "new data";}?>

# For example, beets and carrots are not fruits...$fruit_inventory = array_remove_key($fruit_inventory,"beets","carrots");echo "<pre>Array after key removal:\n",print_r($fruit_inventory,TRUE),'</pre>';

In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.As implied by the manual, however, one can't unset the entire array by passing it by reference.

In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in <?phpunset($undefinedVariable);?>does not trigger an "Undefined variable" notice. But<?phpunset($undefinedArray[$undefinedKey]);?>triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!

>For the curious: unset also frees memory of the variable used.>>It might be possible that the in-memory size of the PHP Interpreter isn't reduced, but your scripts won't touch the memory_limit boundary. Memory is reused if you declare new variables.

It might be worth adding that functions apparently don't free up memory on exit the same way unset does..Maybe this is common knowledge, but although functions destroys variables on exit, it (apparently) doesn't help the memory.

So if you use huge variables inside functions, be sure to unset them if you can before returning from the function.

In my case, if I did not unset before return, then the script would use 20 MB more of memory than if I did unset.This was tested with php 5.0.4 on apache 2 on windows xp, with no memory limit.

Before I did the test, I was under the impression that when you exit from functions, the memory used inside it would be cleared and reused. Maybe this should be made clear in the manual, for either unset() or in the chapter for functions.

Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:

<?php $values = array(5, 10, 15, 100); //array of values that we wish to add to our new array

Please note that PHP doesn't have magic callback to unset overloaded properties. This is the reason why unset($SomeObj->Virtual1) doesn't work.

But it does work when we set 'null' value such as the following code:<?php// now we will set 'null' value instead of using unset statement$SomeObj->Virtual1 = null;$SomeObj->{'Virtual'.(3)} = null;

// and now these variables are no longer availableprint $SomeObj->Virtual1."\n"; print $SomeObj->{'Virtual'.(3)}."\n";?>Sound ugly, yeah?

This applied to the "virtual" array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.

"It is possible to unset even object properties visible in current context"

Although the note is clear, in my case it required a little example to grasp its full impact:

If your object uses overloaded properties (using the "__set()" magic method) and you unset one of your "real" properties, the "__set()" method will take over if you try to assign a value to this property again. In most cases, the "__set()" method is very much limited in the properties it can set. In my case, I only allow "__set()" to change a limited, predefined, set of properties. Most of them through their "public" name instead of their actual name...

This generates a somewhat counter-intuitive situation: If you unset a variable, you expect its value to become "null", which remains true. You also expect to be able to set it again to another value.In the example described above this is not the case: The "__get()" method is invoked and, in my case, doesn't allow the property to be set again!

If one tries to unset a typical variable that does not exist, no errors, warning or noticies will occur. However, if one tries to unset a non-existent array or an array with non-existent key, this will result in a notice. For instance:

unset($class_object) does not release resources allocated by the object. If used in loops, which create and destroy objects, that might easily lead to a resource problem. Explicitly call the destructor to circumvent the problem.