0
0
PhpHow-ToBeginner · 3 min read

How to Use unset in PHP: Remove Variables and Array Elements

In PHP, use the unset() function to delete a variable or an element from an array. This removes the variable or array key from memory, making it undefined afterward.
📐

Syntax

The unset() function takes one or more variables or array elements as arguments and deletes them. After calling unset(), the variable or element no longer exists.

  • unset($var); deletes a variable.
  • unset($array['key']); deletes an array element.
php
unset(mixed &$var, mixed &...$vars): void
💻

Example

This example shows how to remove a variable and an array element using unset(). After unsetting, trying to access them will show they no longer exist.

php
<?php
// Define a variable
$name = "Alice";
// Define an array
$fruits = ["apple", "banana", "cherry"];

// Remove the variable
unset($name);

// Remove the second element from the array
unset($fruits[1]);

// Check if variable exists
if (isset($name)) {
    echo "Name is set\n";
} else {
    echo "Name is unset\n";
}

// Print the array after unset
print_r($fruits);
?>
Output
Name is unset Array ( [0] => apple [2] => cherry )
⚠️

Common Pitfalls

Common mistakes when using unset() include:

  • Trying to unset a variable that does not exist (no error, but no effect).
  • Expecting unset() to reindex arrays automatically (it does not; keys remain as-is).
  • Using unset() on function parameters inside the function (it only unsets the local copy).
php
<?php
// Wrong: expecting array keys to reindex
$arr = ["a", "b", "c"];
unset($arr[1]);
print_r($arr); // keys are 0 and 2, not reindexed

// Right: reindex manually if needed
$arr = array_values($arr);
print_r($arr); // keys are 0 and 1
?>
Output
Array ( [0] => a [2] => c ) Array ( [0] => a [1] => c )
📊

Quick Reference

Summary tips for using unset():

  • Use unset() to delete variables or array elements.
  • It does not reindex arrays; use array_values() to reindex.
  • After unset(), the variable or element is undefined.
  • Multiple variables can be unset at once: unset($a, $b, $c);

Key Takeaways

Use unset() to remove variables or specific array elements in PHP.
Unset array elements keep their keys; use array_values() to reindex if needed.
After unsetting, variables or elements no longer exist and cannot be accessed.
You can unset multiple variables or elements in one call by separating them with commas.
Unset only affects the current scope; unsetting function parameters only removes the local copy.