Search code examples
phpvariablesreference

PHP remove "reference" from a variable.


I have the code below. I want to change $b to use it again with values. If I do so it changes $a as well. How can I assign a value to $b again after previously assigning it as a reference to $a?

$a = 1;
$b = &$a;

// later
$b = null;

Solution

  • See explanation inline

    $a = 1;    // Initialize it
    
    $b = &$a;  // Now $b and $a becomes same variable with 
               // just 2 different names  
    
    unset($b); // $b name is gone, vanished from the context.
               //  But $a is still available
    
    $b = 2;    // Now $b is just like a new variable with a new value.
               // Starting a new life.