What is the PHP unset() function?
The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so. The unset() function has no return value.
The illustration below explains how a variable is unset():
Examples
Code 1
The coded example below unsets the local variable:
<?php$my_var='Hello User';echo " before unset : ".$my_var;echo"\n";unset($my_var);echo "after unset : " .$my_var;?>
Code 2
The coded example below unsets the global variable using $GLOBALS array:
<?php$my_var='Hello User';function unset_var(){global $my_var;echo "Before unset and inside function : ".$my_var."\n";unset($GLOBALS['my_var']);}echo "Outside function before using function : ".$my_var."\n";unset_var();echo "Outside function after using function : ".$my_var."\n";?>
The error in the codes occurred because the code tried to print the unset variable.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved