php[tek] 2018 : Call for Speakers

unset

(PHP 4, PHP 5, PHP 7)

unsetDétruit une variable

Description

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

unset() détruit la ou les variables dont le nom a été passé en argument var.

Le comportement de unset() à l'intérieur d'une fonction peut varier suivant le type de variable que vous voulez détruire.

Si une variable globale est détruite avec unset() depuis une fonction, seule la variable locale sera détruite. La variable globale gardera la valeur acquise avant l'appel à unset().

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

$foo 'bar';
destroy_foo();
echo 
$foo;
?>

L'exemple ci-dessus va afficher :

bar

Pour détruire une variable globale à l'intérieur d'une fonction, vous pouvez utiliser le tableau $GLOBALS :

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

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

Si une variable qui est passée par référence est détruite à l'intérieur d'une fonction, seule la variable locale sera détruite. La variable globale conservera la même valeur qu'elle avait avant l'appel de unset().

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

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

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

L'exemple ci-dessus va afficher :

truc
truc

Si une variable statique est détruite à l'intérieur d'une fonction unset() détruira la variable seulement dans le contexte du reste de la fonction. Les appels suivants restaureront la valeur précédente de la variable.

<?php
function foo()
{
    static 
$bar;
    
$bar++;
    echo 
"Avant unset : $bar, ";
    unset(
$bar);
    
$bar 23;
    echo 
"après unset : $bar\n";
}

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

L'exemple ci-dessus va afficher :

Avant unset : 1, après unset: 23
Avant unset : 2, après unset: 23
Avant unset : 3, après unset: 23

Liste de paramètres

var

La variable à détruire.

...

Autres variables...

Valeurs de retour

Aucune valeur n'est retournée.

Exemples

Exemple #1 Exemple avec unset()

<?php
// Destruction d'une seule variable
unset($foo);

// Destruction d'un élément de tableau
unset($bar['quux']);

// Destruction de plusieurs variables
unset($foo1$foo2$foo3);
?>

Exemple #2 Exemple avec un transtypage (unset)

Le transtypage (unset) est souvent confondu avec la fonction unset(). Le transtypage (unset) sert uniquement à transtyper en type NULL. Il n'altère pas la variable transtypée.

<?php
$name 
'Felipe';

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

L'exemple ci-dessus va afficher :

NULL
string(6) "Felipe"

Notes

Note: Comme ceci est une structure du langage, et non pas une fonction, il n'est pas possible de l'appeler avec les fonctions variables.

Note:

Il est possible de détruire n'importe quelle propriété visible dans le contexte courant.

Note:

Il n'est pas possible de détruire la variable spéciale $this à l'intérieur d'une méthode d'un objet, depuis PHP 5.

Note:

Lors de l'utilisation de cette fonction sur des propriétés d'objet inaccessibles, la méthode magique __unset sera appelée, si elle existe.

Voir aussi

  • isset() - Détermine si une variable est définie et est différente de NULL
  • __unset()
  • empty() - Détermine si une variable est vide
  • array_splice() - Efface et remplace une portion de tableau

add a note add a note

User Contributed Notes 31 notes

up
90
Phantasma_9 at yahoo dot com
1 year ago
This is probably trivial but there is no error for unsetting a non-existing variable.
up
61
Hayley Watson
4 years ago
You don't need to check that a variable is set before you unset it.
<?php
unset($a);
?>
is harmless.
<?php
if(isset($a)) {
    unset(
$a);
}
?>
is pointless complication.

This doesn't apply to properties of objects that have __isset() methods that visibly change object state or __unset() methods that don't properly check their arguments or have extra side effects.

The latter case means that __unset shouldn't do more than what it says on the tin, and also has the responsibility for checking (possibly using __isset()) that what it's being asked to do makes sense.

The former case is just plain bad design.
up
44
Kai Kunstmann
9 years ago
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.
up
37
j dot vd dot merwe at enovision dot net
7 years ago
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).
up
36
franckraynal at free dot fr
12 years ago
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.
up
30
nox at oreigon dot de
9 years ago
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.
up
29
andre at twg dot com dot au
13 years ago
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
up
20
hessodreamy at gmail dot com
10 years ago
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.
?>
up
16
phpmanual at kennel17 dot co dot uk
7 years ago
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)
up
18
dan AT --nospam-- cubeland DOT co DOT uk
13 years ago
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:
*/
?>
up
17
Anonymous
10 years ago
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
?>
up
15
anon at no spam dot no address dot com
13 years ago
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.
up
11
pfreilly at umd dot umich dot edu
6 years ago
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
up
12
dibakar dot datta at gmail dot com
11 years ago
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.
up
12
no at spam dot com
12 years ago
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.
up
9
edouard dot berge at gmail dot com
7 years ago
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
up
11
clark at everettsconsulting dot com
12 years ago
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 )

?>
up
8
lion_cat at mail ru
9 years ago
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!!!
up
9
thorry at thorry dot net
13 years ago
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

emory uss="default">wh=lo, ry uss=6span>
folasshref="#56661" class="name"> clark at everettsconsulting dot com
12 years ago
\n"4Bie(