PHP unset Function Tutorial with Examples

Last Updated on by in PHP
In this PHP 8 tutorial, we will find out how to use unset function in PHP programme. PHP offers a various powerful in-built functions.In PHP, the unset() function is used to destroy the given variable. However, the behavior of unset() function totally depends on what kind of variable you are trying to destroy.

If you are trying to unset() global variable within the function, then the local variable within the function will be destroyed. This function is mostly used for local variables.

But if you are trying to unset the global variables within the function then you must use $GLOBALS array.

Understand unset syntax

The unset parameter takes one parameter, which is the variable to be passed. And it doesn’t return anything.

Parameter Description
$variable The $variable is a required parameter, pass the variable which needs to be destroyed or unset.

Remove Variable using unset

As you can see in the below example, we have defined a variable and unset_var() method.

However, this function is not considering the variable called outside the function. It is destroying the variable from the user defined function.


      $variable = "John Doe"; 
      function unset_var() { 
      echo $variable; 



// output: John Doe

Another Example:

      $variable = "John Doe"; 
      echo "unset not applied : ".$variable;
      echo "<br>";
      echo "unset applied : " .$variable;

/* output:
unset not applied : John Doe
unset applied :

Remove Array Items using unset

The unset function in php can be used to remove array items. We can take help of array key to delete an array’s item.

Remove Array Item using Array Key

  $names = array("john", "anna", "sam", "henry", "vernoica"); 
  while (list ($key, $val) = each ($names)) {
      echo "$key -> $val <br>";


/* output:
  0 -> john 
  1 -> anna 
  3 -> henry 
  4 -> vernoica 

You can see in the example we are removing the 2nd index from the array. We passed the array key in the unset() function.

It removed the element from the array like it use to destroy variables. If you pass the non-existing array key in the unset() function, it won’t throw any error in that case.


Finally, we are done with PHP unset() function tutorial with examples.

I hope this PHP tutorial will help you and also include a new weapon in your programming arsenal.

Please share this tutorial with others, if you liked this tutorial.