2
<?php

$arr = array(1);
$a =& $arr[0];
$arr2 = $arr;
$arr2[0]++;

var_dump($arr);

This portion of code outputs 2. Why?

We only touched first element of arr2 which isn't assigned by reference to $arr. Doesn't alias to the same array, so why is that?

Krystian Polska
  • 1,286
  • 3
  • 15
  • 27
  • Because $arr2 is incremented by 1 at the end, and it's assigned what was in $arr. I suggest print_r($arr) and look into it there. Not exactly sure what you're trying to accomplish in this though – clearshot66 Aug 31 '17 at 19:25

1 Answers1

2

When you assign one array to the next, a copy is made. But because the element at $arr[0] is a reference rather than a value, a copy of the reference is made, so that at the end, $arr[0] and $arr2[0] refer to the same thing.

This is more about references than arrays. Referenced values are not copied. This applies to objects as well. Consider:

$ageRef = 7;

$mike = new stdClass();
$mike->age = &$ageRef; // create a reference
$mike->fruit = 'apple';

$john = clone $mike; // clone, so $mike and $john are distinct objects
$john->age = 17; // the reference will survive the cloning! This will change $mike
$john->fruit = 'orange'; // only $john is affected, since it's a distinct object

echo $mike->age . " | " . $mike->fruit; // 17 | apple

See the first user note on this documentation page and also this one.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • This is weird. It doesn't seem like creating a reference to `$arr[0]` should also turn `$arr[0]` into a reference. I'm surprised that I haven't accidentally run across this by now. – Don't Panic Aug 31 '17 at 19:44