PHP unset() function

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.

Note: A variable will not be considered to be set for so long if it is unset using the unset() function.

Syntax

Mixed denotes that the parameter can be multiple types.

Parameters

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.

Return Values

No value is returned by the unset() function.

Examples

Below some examples are given through which you can understand the working of the unset() function:

Example 1:

Output:

Before using unset() the domain name of website is : tutorialsinfo.com

Notice: Undefined variable: website in C:\xampp\htdocs\program\unset.php on line 5
After using unset() the domain name of website is :

Example 2: Use of unset()

In this example, we will use the unset() function to destroy the variable. Look at the below example:

Output:

Variable before unset : test
bool(true)
Notice: Undefined variable: var_value1 in C:\xampp\htdocs\program\unset.php on line 10

Variable after unset :
bool(false)

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.

Output:

Welcome to w3cschoool.

Example 4: Unset global variable when changes reflect

Use the $GLOBAL array to unset a global variable inside a function.

Output:

Notice: Undefined variable: var_value1 in C:\xampp\htdocs\program\unset.php on line 11

Example 5: Destroy static variable

Output:

Value before unset: 1, Value after unset: 25
Value before unset: 2, Value after unset: 25
Value before unset: 3, Value after unset: 25

Next TopicPHP Tutorial




Contact US

Email:[email protected]

PHP unset() function
10/30