Monday, May 11, 2026
HomeLanguagesPHP | unset() Function

PHP | unset() Function

The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it.

It means that this function unsets only local variable. If we want to unset the global variable inside the function then we have to use $GLOBALS array to do so.

Syntax

unset($variable)

Parameter

  • $variable: This parameter is required, it is the variable which is needed to be unset

Return Value: This function does not returns any value.

Below programs illustrate the unset() function in PHP:

Program 1:




<?php
  
      $var = "hello";
        
      // No change would be reflected outside
      function unset_value()
      {
          unset($var);
      }
        
      unset_value();
      echo $var;
?>


Outside:

hello

Program 2:




<?php
     
      $var = "hello";
        
      // Change would be reflected outside the function 
      function unset_value()
      {
          unset($GLOBALS['var']);
      }
        
      unset_value();
      echo $var;
?>


Output:

No Output

Program 3:




<?php
      
      // user-defined function
      function unset_value()
      {
          static $var = 0;
          $var++;
            
          echo "Before unset:".$var." ";
            
          unset($var);
      
          // This will create a new variable with
          // existing name
          $var = 5;
           
          echo "After unset:".$var."\n";          
      }
        
      unset_value();
      unset_value();
      unset_value();
      unset_value();
        
?>


Output:

Before unset:1 After unset:5
Before unset:2 After unset:5
Before unset:3 After unset:5
Before unset:4 After unset:5

Note: If a variable is declared static and if it is unset inside the function then, the affect will be in the rest of context of a function only. Above calls outside the function will restore the value.

Reference:
http://php.net/manual/en/function.unset.php

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS