Skip to content

unset()

Introduction

The unset() function is a built-in function in PHP that destroys a variable or an element of an array. It can be used to remove variables or elements that are no longer needed. Note that while unset() removes the variable or array element, actual memory deallocation is handled by PHP's garbage collector rather than happening immediately.

Syntax

The syntax of the unset() function is as follows:

The PHP syntax of the unset()

php
void unset(mixed $var[, mixed $... ])

The function takes one or more parameters. Each parameter represents the variable or the element of an array to be destroyed.

Example Usage

Here is an example of how to use the unset() function in PHP:

Example of PHP unset()

php
<?php
$array = ["apple", "banana", "cherry"];
unset($array[1]);
print_r($array);
?>

In this example, we define an array $array containing three elements. We use the unset() function to remove the second element of the array, which has an index of 1. We then use the print_r() function to print the resulting array to the output. The output shows the contents of the array with the second element removed:

console
Array
(
    [0] => apple
    [2] => cherry
)

Unsetting a standalone variable

php
<?php
$name = "John";
unset($name);
echo $name ?? "Variable is unset"; // Outputs: Variable is unset
?>

Conclusion

The unset() function is a useful tool for removing variables or elements that are no longer needed in PHP. It can be used to remove elements from an array or to destroy standalone variables. While it removes the reference to the variable or element, actual memory deallocation is managed by PHP's garbage collector. By using this function, developers can clean up their code and avoid unnecessary references. However, it is important to use this function carefully and ensure that the variables or elements to be destroyed are no longer required.

Practice

What is the primary function of the 'unset()' function in PHP?

Dual-run preview — compare with live Symfony routes.