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?

1
  • 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 Commented Aug 31, 2017 at 19:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.