PHP unset Function Tutorial with Examples

By Digamber Rawat Last updated on
In this PHP 7 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.

unset($variable)
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.

<?php 

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

?> 

Result:

// output: John Doe

Another Example:

<?php 
  
      $variable = "John Doe"; 
      
      echo "unset not applied : ".$variable;
      echo "<br>";
      unset($variable);
      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

<?php 
  
  $names = array("john", "anna", "sam", "henry", "vernoica"); 
  
  unset($names[2]);
  
  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.

Conclusion

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.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me