The php unset() function destroys one or more variables. We can use unset() to delete previously declared variables.
$variable = "I'm a variable";
echo var_dump(isset($variable));
unset($variable);
echo var_dump(isset($variable));
//Output:
bool(true)
bool(false)
When working with variables in our php programs, it is useful to be able to delete a variable. In php, the unset() function allows us to delete variables.
You can pass one or more variables to unset() and unset() will delete those variables.
Below is an example of how to use unset() to delete a variable in php. We can verify that the variable has been deleted with the php isset() function.
$variable = "I'm a variable";
echo var_dump(isset($variable));
unset($variable);
echo var_dump(isset($variable));
//Output:
bool(true)
bool(false)
Deleting Multiple Variables with unset() Function in php
With the php unset() function, we can delete multiple variables.
To delete multiple variables, pass the variables separated by commas to unset().
Below is an example of how to use unset() to destroy multiple variables in php. We can verify that all the variables has been deleted with the isset() function.
$variable1 = "I'm a variable";
$variable2 = "I'm another variable";
echo var_dump(isset($variable1, $variable2));
unset($variable1, $variable2);
echo var_dump(isset($variable1, $variable2));
//Output:
bool(true)
bool(false)
Hopefully this article has been useful for you to learn how to use the php unset() function to destroy previously declared variables in your php code.