unset()

Description

This function “unsets” (destroys) one or variables passed as arguments. If called on a global variable used within a function, only the local variable will be destroyed; the global variable will retain its value. If unset() is passed a variable that is passed by reference to a function, only the local version will be destroyed; the variable outside the function will retain its value.

Syntax


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

Parameters

$var
The variable to be destroyed.

Return Value

void
This function has no return value.

Examples

1. Unset Variable and Array Element

This example creates variables of type integer and array and prints their types and values with var_dump(). It then unsets the integer and the second element of the array with unset() and again prints their types and values.

<?php
echo "setting variables...\n";
$intVal = 6;
$arrayVal = array( 1, 2, 3);
var_dump( $intVal );
var_dump( $arrayVal );

echo "unsetting variables...\n";
unset( $intVal );
unset( $arrayVal[1] );
var_dump( $intVal );
var_dump( $arrayVal );
?>

The output below shows the contents of the integer and array variables before and after the unset() call. Notice that the integer variable is completely destroyed and an error message is generated. However, in the case of the array, only the second element is destroyed. The first and third elements still exist and are printed.

setting variables...
int(6)
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
unsetting variables...
PHP Notice:  Undefined variable: intVal in /home/charlie/php/unset.php on line 11
NULL
array(2) {
  [0]=>
  int(1)
  [2]=>
  int(3)
}

2. Unset Global Within Function

Description of example….

<?php
function f()
{
  global $intVal;
  echo 'in f() $intVal == ' . $intVal . "\n";
  unset( $intVal );
}

$intVal = 6;
echo 'before f() $intVal == ' . $intVal . "\n";
f();
echo 'after f() $intVal == ' . $intVal . "\n";
?>
before f() $intVal == 6
in f() $intVal == 6
after f() $intVal == 6

3. Unset Reference Within Function

Description of example….

<?php
function f( &$intVal )
{
  echo 'in f() $intVal == ' . $intVal . "\n";
  unset( $intVal );
}

$intVal = 6;
echo 'before f() $intVal == ' . $intVal . "\n";
f( $intVal );
echo 'after f() $intVal == ' . $intVal . "\n";
?>
before f() $intVal == 6
in f() $intVal == 6
after f() $intVal == 6

See Also

References