Unset function in PHP

Last updated 5 years, 7 months ago | 1318 views 75     5

Tags:- PHP

PHP | unset() function

The function unset() is an inbuilt function in in php which is use to delete variable.

unset($var)

or

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

Note: we can pass multiple variable by applying comma to separate the variable (i.e.: unset($var, $var1, ...)).

The behavior of unset() function is depending on the type of variable which is going to be delete.

So if we try to delete a global variable inside a function using unset() function then it will delete only local variable means it is not going to affect anything to the global variable. The calling of the variable will print the same value as before unset() was called.

<?php
       
      // No changes would be reflected outside of function
      function unset_val()
      {
        global $var;
        unset($var);
      }
      $var = "hello php";
       
      unset_val();
      echo $var;

?>

To delete a global variable inside of a function, we have to use $GLOBALS keyword.

$GLOBALS is a super global variable in php which is used to access global variables from anywhere in the php script. It is an array which hold variable name as an index.

Syntax

$GLOBALS[index]
<?php
             
      // Changes would be reflected outside of the function
      function unset_val()
      {
          unset($GLOBALS['var']);
      }

     $var = "hello php";

       
      unset_val();
      echo $var;

?>