English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP unset() Function Usage and Example

PHP Available Functions

unset() The function is used to destroy the given variable.

PHP Version Requirement: PHP 4, PHP 5, PHP 7

Syntax

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

Parameter Description:

  • $var: The variable to be destroyed.

Return Value

No return value.

Online Example

<?php
// Destroying a Single Variable
unset ($foo);
// Destroying a Single Array Element
unset ($bar['quux']);
// Destroying Multiple Variables
unset($foo1, $foo2, $foo3);
?>

If a global variable is unset() within a function, only the local variable is destroyed, and the variable in the calling environment will maintain the value before calling unset().

<?php
function destroy_foo() {
    global $foo;
    unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>

Output Result:

bar

If you want to unset() a global variable within a function, you can use the $GLOBALS array to achieve this:

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

If a variable passed by reference is unset() within a function, only the local variable is destroyed, and the variable in the calling environment will maintain the value before calling unset().

<?php
function foo(&$bar) {
    unset($bar);
    $bar = "blah";
}
$bar = 'something';
echo "$bar\n";
foo($bar);
echo "$bar\n";
?>

The following example will output:

something
something

If a static variable is unset() within a function, the static variable will be destroyed within the function. However, when the function is called again, the static variable will be restored to the value before it was destroyed.

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

The following example will output:

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

PHP Available Functions