Search code examples
phpvariablesoperatorsassignment-operator

What is the difference between “=” and “=&” when assigning variables?


I am trying to figure out the difference between $a=&$b and $a=$b. I know & make the variable to be a reference variable. But the following test gave me the same result. Can anyone explain the difference? Thanks.

 $a=5;
 $b=6;

 $a=&$b;
 echo $a; //6


 $a=5;
 $b=6;

 $a=$b;
 echo $a; //6

Solution

  • First of all: you'll hardly ever need references, avoid the confusion of using them if you can.

    $a=5;    //assign value to a
    $b=&$a;  //make $b a reference to $a
    $b=6;    //assigning a value to $b assigns the same value to $a (as they point to the same location
    echo $a; //6
    
    
    $a=5;    //assign a value to a
    $b=$a;   //set $b to the value of $a
    $b=6;    //set $b to another value leaves $a at it's original value
    echo $a; //5