The unset() function is a predefined variable handling function of PHP, which is used to unset a specified variable. In other words, "the unset() function destroys the variables".
The behavior of this function varies inside the user-defined function. If a global variable is unset inside a function, the unset() will destroy it locally and leave the same value initially provided for outside. Use the $GLOBALS array to destroy a global variable inside the function.
unset (mixed variable, ….)
Mixed denotes that the parameter can be multiple types.
This function accepts one or more parameters, but atleast one parameter must be passed in this function.
variable (required) - This parameter is mandatory to pass as it holds that variable, which is needed to be unset.
… - More number of variables to be unset, which are optional to pass.
No value is returned by the unset() function.
Below some examples are given through which you can understand the working of the unset() function:
Example 1:
<?php //variable $website is initialized $website='rookienerd.com'; //display the name of the website echo 'Before using unset() the domain name of website is : '. $website. '<br>'; //unset the variable $website unset($website); //It will not display the name of the website echo 'After using unset() the domain name of website is : '. $website; ?>
Output:
Example 2: Use of unset()
In this example, we will use the unset() function to destroy the variable. Look at the below example:
<?php $var_value1 = 'test'; if (isset($var_value1)) { //It will print because variable is set echo "Variable before unset : ". $var_value1; echo "</br>"; var_dump (isset($var_value1)); } unset ($var_value1); echo "</br>Variable after unset : ". $var_value1; echo "</br>"; var_dump (isset($var_value1)); ?>
Output:
Example 3: Unset GLOBAL variable, but no changes reflect
If you directly try to unset the global variable inside a function, the changes will be reflected locally, not globally.
<?php $var_value1 = "Welcome to rookienerd"; // No changes will be reflected outside function unset_var_value() { unset($var_value1); } unset_var_value(); echo $var_value1; ?>
Output:
Example 4: Unset global variable when changes reflect
Use the $GLOBAL array to unset a global variable inside a function.
<?php $var_value1 = "Welcome to rookienerd"; // Changes will be reflected outside function unset_var_value() { unset($GLOBALS['var_value1']); } unset_var_value(); echo $var_value1; ?>
Output:
Example 5: Destroy static variable
<?php function destroy_var() { static $var; $var++; echo "Value before unset: $var, "; unset($var); $var = 25; echo "Value after unset: $var </br>"; } destroy_var(); destroy_var(); destroy_var(); ?>
Output: