PHP unset() Function

PHP 可用的函数PHP Available Functions

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

PHP Version Requirements: 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.

Example

Example

<?php //Destroy a single variable unset ($foo); //Destroy a single array element unset ($bar['quux']); //Destroy more than one variable unset($foo1, $foo2, $foo3); ?>

If you unset() a global variable inside a function, only the local variable is destroyed, and the variable in the calling environment will retain the same value as before the unset() call.

Example

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

The output is:

bar

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

Example

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

If you unset() a variable passed by reference inside a function, only the local variable is destroyed, and the variable in the calling environment will retain the same value as before the unset() call.

Example

<?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 you unset() a static variable inside 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 it had before it was last destroyed.

Example

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

PHP 可用的函数PHP Available Functions

Other Extensions