PHP unset() Function

PHP unset() function is “used to unset a specified variable.” If unset() is called inside a user-defined function, it unsets the local variables. To unset a global variable inside the function, the $GLOBALS array needs to be used.

Syntax

unset ($var1, $var2.... )

Parameters

$var1, $var2: It is the variable which is needed to be unset. You can pass as many variables as possible.

Return value

None.

Visual RepresentationVisual Representation of PHP unset() Function

Example 1: How to Use the unset() Function

<?php

$var = 'Millie Bobby Brown'; 

echo " Before unset : ".$var ."\n";

unset($var);

echo "After unset : " .$var;

Output

Before unset : Millie Bobby Brown
After unset : 

Example 2: unset the global variable

<?php 

$var = 'Millie Bobby Brown';

function eleven()
{
 unset($GLOBALS['var']);
}
echo "Ouside function before using unset: ".$var."\n";
eleven();

echo "Outside function after using unset: ".$var; 

Output

Ouside function before using unset: Millie Bobby Brown
Outside function after using unset: 
To check if the variable is set in PHP, use the PHP isset() function.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.