PHP unset() | Unset a Variable

The PHP unset() function is used when we need to unset a variable. For example:

<?php
   $x = "codescracker.com";
   echo "The value of \$x is $x";
   
   unset($x);
   
   echo "The value of \$x is $x";
?>

The output produced by the above PHP example on the unset() function is:

php unset function

That is:

php unset example

PHP unset() Syntax

The syntax of the unset() function in PHP is:

unset(variableOne, variableTwo, variableThree, ..., variableN);

At least one variable is required. All the variables given as parameters will get unset.

PHP unset a session variable

The PHP unset() function is used most of the time to unset a session variable. So to unset a session variable, follow this way:

unset($_SESSION['login']);

Now the variable login is unset or deleted from the session.

Remove an element from an array using unset() in PHP

unset() can be used to remove an element from an array in PHP. As an example, I'm going to remove the second element (or the element at index number 1) from the array "$fruits". Keep in mind that the array's index always starts with 0. Meaning that $fruits[0] is equal to the first element, $fruits[1] is equal to the second element, and so on.

PHP Code
<?php
   $fruits = array("apple", "grape", "orange", "banana");
   print_r($fruits);

   echo "<hr>";

   // The following statement removes the second element ("grape") from the array.
   unset($fruits[1]);
   print_r($fruits);
?>
Output
Array ( [0] => apple [1] => grape [2] => orange [3] => banana )

Array ( [0] => apple [2] => orange [3] => banana )

The step-by-step explanation of the above PHP example is as follows:

Advantages of the unset() function in PHP

Disadvantages of the unset() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!