How to Use the PHP unset() Function

09/05/2021

Contents

In this article, you will learn how to use the PHP unset() function.

PHP unset() Function

The PHP unset() function is used to destroy a variable or an element of an array. The variable or element is no longer accessible after it has been unset.

Syntax:
<?php
  unset(var_name);
?>
Example:
<?php
  $x = "Hello World!";
  unset($x);
?>

In this example, the variable $x is set to the string “Hello World!” and then unset, so it is no longer accessible.

 

You can also use unset() to remove multiple variables at once:

<?php
  $x = "Hello World!";
  $y = 42;
  $z = array(1, 2, 3);
  unset($x, $y, $z);
?>

In this example, all three variables $x, $y, and $z are unset and are no longer accessible.

 

When using unset() on an array, you can unset a specific element of an array by passing the array variable and the index of the element you want to unset.

<?php
  $colors = array("red", "green", "blue");
  unset($colors[1]);
?>

In this example, the element “green” is removed from the array $colors.

It’s worth noting that unset() only destroys the variable or element, it will not destroy the memory space it occupied. The memory is usually freed by garbage collector, which runs periodically and frees the memory occupied by unset variables.
Additionally, unset() does not generate any error message if the variable does not exist or if it has already been unset.