PHP Unsetting References

In PHP, you can break the binding between a variable and its reference using the unset() function. The unset() function doesn't destroy the content but only decouples the variable from its reference, allowing it to be used independently.

Using unset() Function

The most common way to unset a reference is using the unset() function ?

<?php
$a = 10;
$b = &$a;  // $b is a reference to $a
echo "before unsetting: " . $a . " " . $b . PHP_EOL;
unset($b);  // Remove the reference
echo "after unsetting: " . $a . " ";
$b = 20;    // $b is now a normal variable
echo $b;
?>
before unsetting: 10 10
after unsetting: 10 20

After unsetting, $b can be used as a normal variable without affecting $a.

Using NULL Assignment

References can also be removed by assigning the variable to NULL ?

<?php
$x = 100;
$y = &$x;  // $y is a reference to $x
echo "x and y are references: " . $x . " " . $y . PHP_EOL;
$y = NULL; // Break the reference
$x = 200;  // Only $x changes
echo "x: " . $x . " y: " . $y . PHP_EOL;
?>
x and y are references: 100 100
x: 200 y: 

Key Differences

Method Effect on Variable Memory Usage
unset() Variable becomes undefined Frees memory if no other references
NULL assignment Variable becomes NULL Variable still exists in memory

Conclusion

Use unset() to completely remove a reference variable, or assign NULL to break the reference while keeping the variable. Both methods allow independent manipulation of the original and referenced variables.

Updated on: 2026-03-15T09:15:31+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements