Variable handling 函数
在线手册:中文 英文
PHP手册

unset

(PHP 4, PHP 5)

unset释放给定的变量

说明

void unset ( mixed $var [, mixed $var [, $... ]] )

unset() 销毁指定的变量。注意在 PHP 3 中,unset() 将返回 TRUE(实际上是整型值 1),而在 PHP 4 中,unset() 不再是一个真正的函数:它现在是一个语句。这样就没有了返回值,试图获取 unset() 的返回值将导致解析错误。

Example #1 unset() 示例

<?php
// 销毁单个变量
unset ($foo);

// 销毁单个数组元素
unset ($bar['quux']);

// 销毁一个以上的变量
unset ($foo1$foo2$foo3);
?>

unset() 在函数中的行为会依赖于想要销毁的变量的类型而有所不同。

如果在函数中 unset() 一个全局变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function destroy_foo() {
    global 
$foo;
    unset(
$foo);
}

$foo 'bar';
destroy_foo();
echo 
$foo;
?>
上边的例子将输出:
bar

如果在函数中 unset() 一个通过引用传递的变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function foo(&$bar) {
    unset(
$bar);
    
$bar "blah";
}

$bar 'something';
echo 
"$bar\n";

foo($bar);
echo 
"$bar\n";
?>
上边的例子将输出:
something
something

如果在函数中 unset() 一个静态变量,那么在函数内部此静态变量将被销毁。但是,当再次调用此函数时,此静态变量将被复原为上次被销毁之前的值。

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

foo();
foo();
foo();
?>
上边的例子将输出:
1
2
3

如果您想在函数中 unset() 一个全局变量,可使用 $GLOBALS 数组来实现:

<?php
function foo() {
    unset(
$GLOBALS['bar']);
}

$bar "something";
foo();
?>

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

参见 isset()empty()

参数

var

The variable to be unset.

...

Another variable ...

返回值

没有返回值。

更新日志

版本 说明
4.0.1 Added support for multiple arguments.

范例

Example #2 unset() example

<?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1$foo2$foo3);
?>

Example #3 Using (unset) casting

(unset) casting is often confused with the unset() function. (unset) casting serves only as a NULL-type cast, for completeness. It does not alter the variable it's casting.

<?php
$name 
'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

以上例程会输出:

NULL
string(6) "Felipe"

注释

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

Note:

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

Note:

It is not possible to unset $this inside an object method since PHP 5.

Note:

When using unset() on inaccessible object properties, the __unset() overloading method will be called, if declared.

参见


Variable handling 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 释放给定的变量

用户评论:

pfreilly at umd dot umich dot edu (30-Sep-2011 12:56)

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):

10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5

Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6

50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5

Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5

100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5

Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5

1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391

Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293

10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584

Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701

100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975

Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524

300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512

Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577

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

Metasansana (22-May-2011 05:19)

A simple function to unset unwanted keys in an array:

<?php

        $a
= array("A"=>1, "B"=>2, "C"=>"a");

        foreach(
$a as $key=>&$value){
            if(
is_string($value){
              unset(
$a[$key]);
            }
         }

       
print_r($a);

?>

This should print:  A=1 B=2.

edouard dot berge at gmail dot com (24-Sep-2010 05:09)

Warning!

When unset from an array, if you unset all elements, the array is always set

$tab=array('A'=>1,'B'=>2);
unset($tab['A']);
unset($tab['B']);
echo isset($tab)." ".count($tab);

output: 1 0

Andreas (24-Sep-2010 01:51)

You can not unset a numeric key of an array, if key is a string. See this example:

// Create a simple array with 3 different key types
$test[1] = array(
    10 => array('apples'),
    "20" => array('bananas'),
    '30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} =  array('apples');
$testClass->{"20"} =  array('bananas');
$test[4] = (array) $testClass[6];

echo "<pre>";
foreach($test as $testNum => $arr) {

    echo "\nTest: " . $testNum  . " \n";
    var_dump($arr);

    foreach($arr as $key => $fruit) {
        echo "key: " . $key . "\n";
        echo "key exists: ";
        var_dump(array_key_exists(strval($key), $arr));
        echo "typeof key is: " . gettype($key) . "\n";

        unset($arr[$key]);
    }
    var_dump($arr);
    echo "\n" . str_repeat("-", 80);
}
echo "</pre>";

And here is the output:

Test: 1
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 2
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}

--------------------------------------------------------------
Test: 3
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 4
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}

--------------------------------------------------------------

Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
    $array[intval($key)] = $item;
}

j dot vd dot merwe at enovision dot net (26-Aug-2010 01:08)

A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.

<?php
$db
->set_query("select * from documents where document_in_user = 0"); //1 
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

   
$file     = "uploads/".rawurldecode($row['document_name']);
 
    if (
file_exists ( $file ) == FALSE ) {
         unset(
$documents[$key]);  //3
   

}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).

Anonymous (02-Jul-2010 03:20)

further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:

<?php
class release_test{
  private
$buffer;
  private
$other_object;
  public function
__construct(){
   
$this->other_object=new other_object_class();
  }
  public function
__destruct(){
   
//note that you always have to unset class objects, in order to get the resources released
   
unset($this->other_object);
  }
  public
allocate_mem_A(){
   
$this->buffer=file("/tmp/bigfile");
  }
  public
allocate_mem_B(){
   
$buffer=file("/tmp/bigfile");
  }
  public
allocate_mem_C(){
   
$buffer=file("/tmp/bigfile");
    unset(
$buffer);
  }
  public
allocate_mem_D(){
   
$this->other_buffer=file("/tmp/bigfile");
  }
}

//this does not lead to a resource problem
$A=new release_test();
$A->allocate_mem_A();
$A->__destruct();
unset(
$A);

//this DOES lead to a resource problem
$B=new release_test();
$B->allocate_mem_B();
$B->__destruct();
unset(
$B);

//this does not lead to a resource problem
$C=new release_test();
$C->allocate_mem_C();
$C->__destruct();
unset(
$C);

//this does not lead to a resource problem
$D=new release_test();
$D->allocate_mem_D();
$D->__destruct();
unset(
$D);
?>

alex at bartl dot net (01-Jul-2010 06:11)

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.

<?php
//this causes a resource problem
for($f=0;$f<10000;$f++){
 
$my_class_object=new my_class_name();
  unset(
$my_class_object);
}

//this releases the resources allocate by the object
for($f=0;$f<10000;$f++){
 
$my_class_object=new my_class_name();
 
$my_class_object->__destruct();
  unset(
$my_class_object);
}
?>

alexanderashleyboese at gmail dot com (21-Apr-2010 07:09)

I have noticed that sometimes if you have a globally declared instantiation of a class, unsetting that instance does not always call destruct like you think it should.

For instance, something like this might actually call the destruct later than implied by the "unset":

<?php
class Data {

public function
__destruct() {
echo
"These are my last words...";
}

}

function
main(){
$data = new Data;
one();
two();
}

function
one ()
{
global
$data;
echo
"Running 1st";
unset(
$data);
}

function
two()
{
echo
"Running 2nd";
}

main();

//"Running 1stRunning 2ndThese are my last words..."
?>

phpmanual at kennel17 dot co dot uk (26-Feb-2010 04:55)

Note that PHP 4 will generate a warning if you try to unset an array index that doesn't exist and whose parent doesn't exist.

Example:

<?php

  $foo
= array();

  unset(
$foo['Bar']['Baz']);

?>

RESULT: "Notice:  Undefined index:  Bar"

On PHP5 no error is raised, which seems to me like the correct behaviour.

Note that using unset($foo['Bar']) in the above example does not generate a warning in either version.

(Tested on 4.4.9 and 5.2.4)

obsidianproject.co.uk (10-Sep-2009 02:41)

A quick note on (unset) vs unset().

<?php
$a
="test";
unset(
$a);
var_dump($a);
?>
will return

Notice: Undefined variable: a
NULL

<?php
$a
="test";
var_dump((unset) $a);
?>
will return

NULL

When using unset() php will throw an E_NOTICE if you try and access the variable after it has been unset, (unset) won't.

This has been tested in PHP 5.3.0

David Sawyer, Metaface Development (24-Apr-2009 05:26)

Here's a simple function to remove a variable from an HTTP Query String:

<?php

function unset_query_string_var($varname,$query_string) {
   
$query_array = array();
   
parse_str($query_string,$query_array);
    unset(
$query_array[$varname]);
   
$query_string = http_build_query($query_array);
    return
$query_string;
}

?>

----------------------------

Example Usage #1:
Let's say you want to remove the variable "fruit" from $page_url below...

<?php
$page_url
= "http://www.example.com/script.php?fruit=apple&color=red";
$url_data = parse_url($page_url);
$query_string = unset_query_string_var("fruit",$url_data['query']);
$page_url_new = $url_data['scheme'].'://'.$url_data['host'].$url_data['path'];
if (!empty(
$query_string)) $page_url_new .= '?'.$query_string;
$page_url_new .= $url_data['fragment'];
print
$page_url_new;
?>

Output:
http://www.example.com/script.php?color=red

----------------------------

Example Usage #2:
To remove the variable "q" from the query string of the current page, try something like...

<?php

$page_url
= 'http://'.$_SERVER["SERVER_NAME"].$_SERVER['PHP_SELF'];
$query_string = unset_query_string_var("q",$_SERVER["QUERY_STRING"]);   
if (!empty(
$query_string)) $page_url .= '?'.$query_string;

?>

macnimble at gmail dot com (26-Mar-2009 10:39)

Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
 
$args  = func_get_args();
  return
array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
 
$args = func_get_args();
  return
array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
 
'apples' => 52,
 
'bananas' => 78,
 
'peaches' => 'out of season',
 
'pears' => 'out of season',
 
'oranges' => 'no longer sold',
 
'carrots' => 15,
 
'beets' => 15,
);

echo
"<pre>Original Array:\n",
    
print_r($fruit_inventory,TRUE),
    
'</pre>';

# 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>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                     
"out of season",
                                     
"no longer sold");
echo
"<pre>Array after value removal:\n",
    
print_r($fruit_inventory,TRUE),
    
'</pre>';
?>

lion_cat at mail ru (12-Nov-2008 10:22)

about unset for arrays

if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

after addition a new member by $ar[]=7,

you will get
$ar[0]==2
$ar[1]==7
$ar[3]==7,

So, unset has no effect to internal array counter!!!

thijs NOSPACE putman at gmail dot com (05-Nov-2008 01:17)

"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!

molotster on google mail com (14-Oct-2008 01:50)

unset() does just what it's name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

If you are doing $whatever = null; then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.

nox at oreigon dot de (05-Aug-2008 08:24)

if you try to unset an object, please be careful about references.

Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!

<?php

class A {
  function
__destruct() {
    echo
"cYa later!!\n";
  }
}

$a = new A();
$a -> a = $a;
#unset($a); # Just uncomment, and you'll see

echo "No Message ... hm, what now?\n";
unset(
$a -> a);
unset(
$a);

echo
"Finally that thing is gone\n";

?>

Of course the object completely dies at the end of the script.

stacionari at gmail dot com (17-Mar-2008 09:41)

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
   
   
$myArray = array(4=>0);   //sets starting key to be 4 and assigns some value (lets say 0)
   
unset($myArray[4]);   //delete this index key, but preserves further enumeration
   
   
foreach($values as $value){
       
$myArray[] = $value;   //asign values to our array
   
}
   
   
print_r($myArray);

/* Output:

Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )

*/

?>

pauljamescampbell at gmail dot com (15-Mar-2008 01:22)

Here's my variation on the slightly dull unset method. It throws in a bit of 80's Stallone action spice into the mix. Enjoy!

<?php
/**
 * function rambo (first blood)
 *
 * Completely and utterly destroys everything, returning the kill count of victims
 *
 * @param    It don't matter, it’s Rambo baby
 * @return    Integer    Body count (but any less than 500 and it's not really worth mentioning)
 */
function rambo() {

   
// Get the victims and initiate that body count status
   
$victims = func_get_args();
   
$body_count = 0;   
   
   
// Kill those damn punks
   
foreach($victims as $victim) {
        if(
$death_and_suffering = @unset($victim)) {
           
$body_count++;
        }
    }
   
   
// How many kills did Rambo tally up on this mission?
   
return($body_count);
}
?>

Kai Kunstmann (10-Mar-2008 01:09)

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.

levitating at gmail dot com (07-Jan-2008 12:19)

>> shame, but it doesn't seem to pop the stack.

There is a simple solution to that. Delete the value, then use array_merge() on your array:

<?php $folders= array_merge($folders) ; ?>

Maresa (16-Oct-2007 01:41)

Note that since unset() returns void, you can't do this:

isset($some_var) && unset($some_var);

You'll get: Parse error: syntax error, unexpected T_UNSET in ...

The reason is because it would parse as
<bool> && <void>;
which is not a valid PHP statement.

Thus, the only alternative is to actually use if statement.

gerry+phpnet at buzka dot com (20-Sep-2007 05:07)

Quote from http://fr.php.net/session_unset

"Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal."

So basically don't do:
unset($_SESSION)

Instead do:
$_SESSION = array();

Hayley Watson (24-Aug-2007 05:02)

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
<?php
unset($undefinedVariable);
?>
does not trigger an "Undefined variable" notice. But
<?php
unset($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!

Sinured (17-Jul-2007 05:08)

The main difference between <?php unset($var);?> and <?php $var = null;?> is, that unset() will reset the state to $var to something like "not set at all".

<?php
// register_globals = Off
error_reporting(E_ALL);
echo
$var; // Notice

$var = null;
echo
$var; // Nothing

unset($var);
echo
$var; // Notice
?>

chris at maedata dot com (18-Jun-2007 06:35)

Regarding the 14-May-2007 note from anonymous:

As far as array elements go, unset() is really only useful for removing named keys. For numeric keys, you can use array_splice to "unset" the element.

<?php
$a
= array(
   
'foo' => array('a', 'b', 'c'),
   
'bar' => array('d', 'e', 'f')
);

print_r($a);

array_splice($a['foo'], 1, 1);

print_r($a);

unset(
$a['foo']);

print_r($a);
?>

chad 0x40 herballure 0x2e com (31-May-2007 03:11)

It is observed on PHP 5.1.6 that <?php unset($this); ?> inside of a method will remove the reference to $this in that method. $this isn't considered "special" as far as unset() is concerned.

(15-May-2007 06:51)

shame, but it doesn't seem to pop the stack.

Array( [1\=>1
         [2\=>2
         [3\=>3
)

then unset($array[2\)

results in:

Array( [1\=>1
         [3\=>3
)

not

Array( [1\=>1
         [2\=>3
)

Shame really

RQuadling at GMail dot com (28-Mar-2007 01:28)

If you want to remove a value from an array, then there is no direct mechanism.

The following function uses the array_keys() function to find the key(s) of the value that you want to remove and then removes the elements for that key.

I've also given some examples and the output.

<?php
/**
  * array array_remove ( array input, mixed search_value [, bool strict] )
  **/
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
   
$a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
    foreach(
$a_Keys as $s_Key) {
        unset(
$a_Input[$s_Key]);
    }
    return
$a_Input;
}
?>

Beside scalar variables (integers, floats, strings, boolean), you can also use arrays as the values you want to remove.

<?php
// Results in array(8, 8.0, '8', '8.0')
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8));

// Results in array(8, 8.0, '8', '8.0', array('8'))
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8), True);
?>

(09-Feb-2007 04:10)

Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn't find reference to this anywhere so I decided to write this.

The difference between using unset and using $myarray=array(); to unset is that obviously the array will just be overwritten and will still exist.

<?php

$myarray
=array("Hello","World");

echo
$myarray[0].$myarray[1];

unset(
$myarray);
//$myarray=array();

echo $myarray[0].$myarray[1];

echo
$myarray;
?>

Output with unset is:
<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Output with $myarray=array(); is:
?>

<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Array
?>

hessodreamy at gmail dot com (17-Jan-2007 11:51)

To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren't already set:

unsetting a non-existent key within an array does NOT throw an error.
<?
$array = array();

unset($array[2]);
//this does not throw an error

unset($array[$undefinedVar]);
//Throws an error because of the undefined variable, not because of a non-existent key.
?>

dibakar dot datta at gmail dot com (01-Apr-2006 07:31)

Instead of using the unset function  for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.

Suppose, if you like to unregister your session store values.
You can use:
 
      $_SESSION = array();

Well this syntax saves lot's of time instead of unsetting each values.

hugo dot dworak at gmail dot com (26-Dec-2005 02:23)

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:

<?php
  $true
= true;
 
$array = array ();
  unset (
$true, $undefinedVariable, $array [$undefinedKey], $undefinedArray [$undefinedKey]);
?>

The output is (PHP 5.0.5):

Notice: Undefined variable: undefinedKey
Notice: Undefined variable: undefinedKey
Notice: Undefined variable: undefinedArray

clark at everettsconsulting dot com (11-Sep-2005 08:50)

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.

<?php
function remove_variable (&$variable// pass variable by reference
{
    unset(
$variable);
}

function
remove_element (&$array, $key) // pass array by reference
{
    unset(
$array[$key]);
}

$scalar = 'Hello, there';
echo
'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

remove_variable($scalar); // try to unset the variable
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

$array = array('one' => 1, 'two' => 2, 'three' => 3);
echo
'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_variable($array); // try to unset the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_element($array, 'two'); // successfully remove an element from the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [three] => 3 )

?>

no at spam dot com (30-Aug-2005 11:22)

In addition to what timo dot hummel at 4fb dot de said;

>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.

tom at diacope dot com (04-Aug-2005 11:51)

when working with $_SESSION or any other array like that and you want to delete part of the session array it's always worked for me to do:

$_SESSION['data'] = NULL;
unset($_SESSION['data']);

muhamad_zakaria at yahoo dot com (05-Jul-2005 03:08)

We have experienced when we applied 'unset' to the overloaded properties (PHP5), consider the code below:
<?php
   
class TheObj {
        public
$RealVar1, $RealVar2, $RealVar3, $RealVar4;
        public
$Var = array();

        function
__set($var, $val) {
           
$this->Var[$var] = $val;
        }
        function
__get($var) {
            if(isset(
$this->Var[$var])) return $this->Var[$var];
            else return -
1;
        }
    }

   
$SomeObj = new TheObj;

   
// here we set for real variables
   
$SomeObj->RealVar1 = 'somevalue';
   
$SomeObj->{'RealVar2'} = 'othervalue';
   
$SomeObj->{'RealVar'.(3)} = 'othervaluetoo';
   
$SomeObj->{'RealVar'.'4'} = 'anothervalue';

   
// and here we set for virtual variables
   
$SomeObj->Virtual1 = 'somevalue';
   
$SomeObj->{'Virtual2'} = 'othervalue';
   
$SomeObj->{'Virtual'.(3)} = 'othervaluetoo';
   
$SomeObj->{'Virtual'.'4'} = 'anothervalue';

   
// now we will try to unset these variables
   
unset($SomeObj->RealVar1);
    unset(
$SomeObj->{'RealVar'.(3)});

   
//the lines below will catch by '__get' magic method since these variables are unavailable anymore
   
print $SomeObj->RealVar1."\n";
    print
$SomeObj->{'RealVar'.(3)}."\n";

   
// now we will try to unset these variables
   
unset($SomeObj->Virtual1);
    unset(
$SomeObj->{'Virtual'.(3)});

   
//but, these variables are still available??? eventhough they're "unset"-ed
   
print $SomeObj->Virtual1."\n";
    print
$SomeObj->{'Virtual'.(3)}."\n";
?>

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 available
   
print $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.

franckraynal at free dot fr (26-Feb-2005 01:02)

Here is another way to make 'unset' work with session variables from within a function :

<?php
function unsetSessionVariable ($sessionVariableName) {
   unset(
$GLOBALS[_SESSION][$sessionVariableName]);
}
?>

May it work with others than me...
F.

bedbin at gmail dot com (02-Feb-2005 02:33)

usefull tip:
if you have session variables like these.
<?php
echo "<pre>";
$_SESSION["num"] = array(1,2,3,4);
var_dump($_SESSION);

echo
"-<br>";
unset(
$_SESSION);
var_dump($_SESSION);
?>
gives out:

array(1) {
  ["num"]=>
  array(4) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
    [3]=>
    int(4)
  }
}
-
NULL

if you use empty instead unset you get same output as first var_dump($_SESSION) gives.
I hope help sb.

Nghia (06-Jan-2005 04:41)

I saw this mentioned somewhere else but if you do

$var = NULL

then I've noticed less memory usuage than with unset(). In fact, unset didn't do anything.

This might be useful if you're doing a php-gtk app, thats starting to consume significant memory over a long period of time. This was the code I used to test

// Check memory before here

for($i = 0; $i < 100; $i++)
{
  $dialog = &new GtkDialog();
  $dialog->realize();
  $dialog->destroy();

  $dialog = NULL;
  //unset($dialog);
}

// Check memory after here

Doing a difference between after and before results in:

Using destroy() and unset() ->  ~31kb
Using $dialog = NULL -> ~13 kb

The expected memory usuage should be 0kb or around there.

harycary at netscape dot net (14-Dec-2004 05:56)

If you ever have to unset all the variables of a class from within a funciton of that class use the following code:

<?php

class User
{

     function
User_login ( ... )
     {...}

     function
User_logout ( $greeting )
     {
         
          ...
          foreach (
array_keys ( get_object_vars ( &$this ) ) as $val)
          {    unset(
$this->$val );    }
         
$this->greeting = $greeting;
          ...

     }

}

?>
If anyone knows of a more effective way please post a reply.

mv at brasil dot com (08-Nov-2004 04:04)

If you want to remove one element of Query String use this function, than place the returned values in <a href="script.php?'. remove_query("arg1") .'">

    function remove_query($key) {
   
        $arrquery = explode("&", $_SERVER["QUERY_STRING"]);
       
        foreach ($arrquery as $query_value) {
       
            $valor = substr($query_value, strpos($query_value, "=") + 1);
            $chave = substr($query_value, 0, strpos($query_value, "="));
            $querystring[$chave] = $valor;
       
        }
       
        unset($querystring[$key]);
       
        foreach ($querystring as $query_key => $query_value) {
   
            $query[] = "{$query_key}={$query_value}";
   
        }
   
        $query = implode("&", $query);

        return $query;
   
    }

dan AT --nospam-- cubeland DOT co DOT uk (04-Nov-2004 07:38)

dh at argosign dot de -
it is possible to unset globals from within functions thanks to the $GLOBALS array:

<?php
$x
= 10;

function
test() {
   
// don't need to do ' global $x; '
   
unset ($GLOBALS['x']);
    echo
'x: ' . $GLOBALS['x'] . '<br />';
}

test();
echo
"x: $x<br />";

// will result in
/*
x:
x:
*/
?>

timo dot hummel at 4fb dot de (07-Sep-2004 02:24)

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.

thorry at thorry dot net (05-Aug-2004 10:15)

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.

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

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

The above example would output:

1
2
3

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

1
1
1

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. "

Example: (tested PHP 4.3.7)
<?php
function foo()
{
   static
$a;
  
$a++;
   echo
"$a\n";
   unset(
$a);
   echo
"$a\n";
   static
$a;   
   echo
"$a\n";
}

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

Would output:

1

1
2

2
3

3

anon at no spam dot no address dot com (17-Jul-2004 05:19)

Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.

Eg you have
<?php
 $x
= array(1, 2);

 for (
$i = 0; $i < 5; $i++)
 {
    unset(
$x[(count($x)-1)]); //remove last set key in the array

   
$x[] = $i;
 }
?>

You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....

but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )

This is since even though the last key is removed, the auto indexing still keeps its previous value.

The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.

The way around this is to use array_pop() instead of unset() as array_pop() refreshes the autoindexing thing for the array.
<?php
 $x
= array(1, 2);

 for (
$i = 0; $i < 5; $i++)
 {
   
array_pop($x); // removes the last item in the array

   
$x[] = $i;
 }
?>

 This returns the expected value of x = Array([0] => 1, [1] => 4);

Hope this helps someone who may need this for some odd reason, I did.

bond at noellebond dot com (26-May-2004 10:34)

Note that though global arrays will not be altered by a function, an array in an object WILL be altered if referenced within one of its methods.  For example:

  function remove_index ($i)
  {
    unset($this->test_array[$i]);
    $temp_array = array_values($this->test_array);
    $this->test_array = $temp_array;
   
  }

Will remove key $i from the object's array and reindex it.

andre at twg dot com dot au (07-Mar-2004 05:16)

Only This works with register_globals being 'ON'.

unset( $_SESSION['variable'] );

The above will not work with register_globals turned on (will only work outside of a function).

$variable = $_SESSION['variable'];
unset( $_SESSION['variable'], $variable );

The above will work with register_globals on & inside a function

warhog at warhog dot net (27-Jan-2004 04:52)

you may wan't to unset all variables which are defined, here's one way:

<?php

function unset_all_vars($a)
{ foreach(
$a as $key => $val)
  { unset(
$GLOBALS[$key]); }
  return
serialize($a); }

unset_all_vars(get_defined_vars());

?>

you can also save than a serialized var of the "memory" and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you've got very large variables.

greetz

kdechant at midwestarts dot com (23-Nov-2003 11:47)

As of PHP version 4.3.3, unset() results in a parse error if it is used with the @ error suppression operator.

For example:

@unset($var); // parse error
unset(@$var); // parse error
unset($var); // okay

frank at agentbrand dot com (09-Nov-2003 05:59)

Use array_values() after unset() to reindex your array.
 Note that unset() removes the index as a key, you will need to reindex your array again to get expected behavior

vmizuba at queens dot org (28-Oct-2003 03:25)

for what it's worth...

in php 4.1, using unset to destroy a session variable, i.e. unset($_SESSION['variable']); destroys it by erasing variable information but leaves behind the variable name appended with a '!' in front of the name in the session file... leaving the session file larger and x bytes wasted depending on the variable name length