What is the function of this "= &" operator in PHP?

6

If I have the code below:

$x = 1;
$y = 1;
if($x =& $y){
   echo "ok";
}else{
   echo "não";
}

No matter what value I put in $x or $y , it always falls in echo "ok" . Now if I do not define one of the variables, it falls in echo "não" :

$x = 1;
// $y = 1;
if($x =& $y){
   echo "ok";
}else{
   echo "não";
}

What does this =& operator check between the two operands?

    
asked by anonymous 07.05.2018 / 01:18

2 answers

7

It will always fall in echo "ok" because this =& is not a comparison operator but rather a assignment by reference .

This operator will actually bind the two variables by reference, that is, by modifying the value of one, the value of the other will be modified after this assignment. Check below for the example:

$x = 1;
$y =& $x;
echo $x; // 1
echo $y; // 1
$x = 2;
echo $x; // 2
echo $y; // 2
    
07.05.2018 / 01:27
4

The $x &= $y causes $x and $y to point to the same location, as it says in the manual, link .

The if has nothing to do with it, if is being executed because the value of $y is different from 0. But this occurs with any assignment operation, such as if($x = 1){} .

When you do:

// $y = 1;
if($x =& $y){
}

There is no value for $y , so it is null / 0 / false and then does not match if . When you set any value other than 0 in $y if will be serviced normally, so it is served using $x = $y .

    
07.05.2018 / 01:28