PHP unset() | Unset a Variable

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

   $x = "";
   echo "The value of \$x is $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:


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
   $fruits = array("apple", "grape", "orange", "banana");

   echo "<hr>";

   // The following statement removes the second element ("grape") from the array.
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!