Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: unset - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

var_dump" width="11" height="7"/> <unserialize
Last updated: Thu, 31 May 2007

view this page in

unset

(PHP 4, PHP 5)

unset — 指定した変数の割当を解除する

説明

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

unset() は指定した変数を破棄します。PHP 3 では、 unset() は常に TRUE(実際には整数値 1) を返していました。 しかし、PHP 4 では unset() は もはや真の意味で関数ではなく、命令となっています。値が返されないため、 unset() の値を取得しようとすると、 パースエラーとなります。

例 2526. 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() したい場合は、 $GLOBALS 配列を使用することが可能です。

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

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

参照渡しされた変数が関数内で unset() された場合に、 ローカル変数のみが破棄されます。呼出側の環境でその変数は、 unset() がコールされる前と同じ値を保持します。

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

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

foo($bar);
echo
"$bar\n";
?>

上の例の出力は以下となります。


something
something

      

静的変数が関数の内部で unset() された場合、 unset() は、その関数の残りのコンテキスト内においてのみ 変数を破棄します。関数を再度コールすると、破棄する前の値が復元されます。

<?php
function foo()
{
    static
$bar;
   
$bar++;
    echo
"Before unset: $bar, ";
    unset(
$bar);
   
$bar = 23;
    echo
"after unset: $bar\n";
}

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

上の例の出力は以下となります。


Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

      

注意: これは、関数ではなく 言語構造のため、可変関数 を用いて コールすることはできません。

isset()empty()array_splice() も参照ください。



var_dump" width="11" height="7"/> <unserialize
Last updated: Thu, 31 May 2007
 
add a note add a note User Contributed Notes
unset
Hayley Watson
24-Aug-2007 01: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!
Anthony Fincher
22-Aug-2007 06:02
In several places, someone has left Polish language text in the English manual.

With the help of http://www.poltran.com/pl.php4 I have translated.   Hopefully someone will correct the text above and remove my note.

It would appear that the text:

   Przykład

   Notatka

   Powyższy przykład wyświetli:

is Polish for:

   Example

   Footnote

   Above-mentioned example will display:

My translation site provided only a poor translation for:

   Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Which came out as:

   As there is element of syntax of language but function not, he (it) can not be evoked using alternate (changeable; variable) function
Anthony Fincher
22-Aug-2007 05:46
In several places, someone has left Polish language text in the English manual.

With the help of http://www.poltran.com/pl.php4 I have translated.   Hopefully someone will correct the text above and remove my note.

It would appear that the text:

   Przykład

   Notatka

   Powyższy przykład wyświetli:

is Polish for:

   Example

   Footnote

   Above-mentioned example will display:

My translation site provided only a poor translation for:

   Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Which came out as:

   As there is element of syntax of language but function not, he (it) can not be evoked using alternate (changeable; variable) function
Sinured
18-Jul-2007 01: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
19-Jun-2007 02: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 11: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 02: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 10: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);
?>
10-Feb-2007 01: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 08: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 04: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 11: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
12-Sep-2005 04: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
31-Aug-2005 07: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
05-Aug-2005 07: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 11: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.
smyle at mailbox dot hu
26-May-2005 03:21
This work for me only _SESSION in quotes:
unset($GLOBALS['_SESSION'][$sessionVariableName]);
franckraynal at free dot fr
26-Feb-2005 10: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 11: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 01: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
15-Dec-2004 02: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
09-Nov-2004 01: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
05-Nov-2004 04: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 10: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 06: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 01: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
27-May-2004 06: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 02: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
28-Jan-2004 01: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 08: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
10-Nov-2003 02: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 12: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

var_dump" width="11" height="7"/> <unserialize
Last updated: Thu, 31 May 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites