0

Consider the following PHP code segment.

$array1 = array(1,20);
$x = &$array1[1];
$array2 = $array1;
$array2[1] = 22;
print_r($array1[1]); // Output is 22

Here, $array2 is not referencing to $array1, but how to change value in $array2 by changing value of $array1?

Pang
  • 9,564
  • 146
  • 81
  • 122
Optimus Prime
  • 308
  • 6
  • 22
  • Hey you may be interested in this post that I just made which is based off this post and goes into detail about why you are seeing this behavior. http://stackoverflow.com/questions/26081106/assign-by-reference-bug – michael.schuett Sep 28 '14 at 04:39

1 Answers1

0

If you want $array2 to be a reference of $array1 then you do the same thing as with $x.

$array2 = &$array1;

Now anything you change in either $array1 or $array2 is visible in both arrays since $array2 is just a reference to $array1.


Update

Thinking about it, what you may be looking at is a way to change a value, but still have a full copy of the arrays. This is doable with an object.

$obj = new stdClass();
$array1 = array(1, 20);
$array1[1] = $obj;
$array1[1]->color = 22;

$array2 = $array1;
$array2[1]->color = 33;

echo $array1[1]->color;  // prints 33

This is because objects are always copied by reference, whereas numbers and strings are copied as is.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • I think his question though he may not know it is a little more indepth. array2 for the index of 1 is actually now a pointer as shown by array1 changing when array2 is changed even though it is not a reference to array1. – michael.schuett Sep 27 '14 at 04:07
  • Yes, internally the language may use a copy on write methodology to avoid many otherwise useless copies. – Alexis Wilke Sep 27 '14 at 04:11
  • In this case I would say that is very dangerous. I personally would not expect the 2nd index of array2 to be a pointer to array1 when it's not assigned as such. – michael.schuett Sep 27 '14 at 04:17