关于“&”在php中使用

$arr1 = array(1);
arr2 = $arr1;
$arr2[0]++;//$arr1[0]=1,$arr2[0]=2

But the following code:

$arr1 = array(1);
$a =& $arr1[0];
$arr2 = $arr1;
$arr2[0]++;//$arr1[0]=2,$arr2[0]=2

When I add $a, the output is different! Why does this happen?

@JakubMatczak Thanks for your professional response.But I still have some question.

$arr1 = array(1, 2);
$a =& $arr1;
$arr2 = $arr1;
$arr2[0]++;
$arr2[1]++;

Why the result of $arr1 is array(1, 2) not array(2, 2)?

This is how references work.

Take a closer look what happens to $arr1 before and after assigning a reference to $a

$arr1 = array(1);
var_dump($arr1);
$a =& $arr1[0];
var_dump($arr1);

The result is:

array(1) { [0]=> int(1) } 
array(1) { [0]=> &int(1) } //it's a reference now!

As you can see, after making $a an reference, also $arr[0] starts being a reference.

As PHP Manual says:

$a and $b point to the same content.

And there's important note:

$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

This may be a little bit confusing at first look, but this is how it works.

Further operations of your code should be clear now:

$arr2 = $arr1; 
$arr2[0]++;

You make a copy of $arr1, so $arr2[0] is also a reference to the same value just like $a and $arr1[0]. Then by incrementing $arr2[0], you're also incrementing $a and $arr[0]` (or actually incrementing target single value of these three references).

i will explain you in simple way about = and & operator

$a = 5;
$b = 10;
$a = $b
echo $a // output is 10
echo $b // output is 10

reason is that = is an assignment operator it just copy the value of vaiable and out in other variable.

$a = 5;
$b = 10;
$a = & $b    // here the address of a is assign to variable b.
echo $a // output is 5
echo $b // output is 5

reason is that & is an reference pointer it can pick the address of vaiable and out in other variable. when you change the value of variable any where it will change the value of other variable.