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

Asked

Viewed 107 times

5

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, always falls in the echo "ok". Now if I don’t define one of the variables, I fall into echo "não":

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

What that operator =& checks between the two operands?

2 answers

7


He will always fall in echo "ok" for this =& is not an operator of comparison rather a attribution by reference.

This operator will actually connect 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 in the example:

$x = 1;
$y =& $x;
echo $x; // 1
echo $y; // 1
$x = 2;
echo $x; // 2
echo $y; // 2

4

The $x &= $y does the $x and $y point to the same location, as stated in the manual, http://php.net/manual/en/language.references.whatdo.php.


The if has nothing to do with that, 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 to $y, consequently it is null/0/false and then doesn’t answer the if. When you define any value other than 0 in the $y the if will be met normally, so is met using $x = $y.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.