W3cubDocs

/PHP

unset

(PHP 4, PHP 5, PHP 7)

unsetUnset a given variable

Description

unset ( mixed $var , mixed ...$vars ) : void

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

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

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

The above example will output:

bar

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

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

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

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

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

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

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

The above example will output:

something
something

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

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

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

The above example will output:

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

Parameters

var

The variable to be unset.

vars

Further variables.

Return Values

No value is returned.

Examples

Example #1 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 #2 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. The (unset) cast is deprecated as of PHP 7.2.0.

<?php
$name = 'Felipe';

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

The above example will output:

NULL
string(6) "Felipe"

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

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.

Note:

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

See Also

© 1997–2020 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://www.php.net/manual/en/function.unset.php