1

Suppose code like this:

$a = [1,2];
$b = &$a;     // $b holds reference to $a
$b[] = 3;     // so this makes $a to {1,2,3}
$b = $a;      // $b now holds COPY of $a (not reference)
$b[] = 4;     // so $a must be the same {1,2,3}
var_dump($a); // but it isn't - $a is {1,2,3,4}

So somehow statement $b = $a; is not allocating a new copy of $a array as it should, but using it's reference only. Why is that ?

Agnius Vasiliauskas
  • 10,935
  • 5
  • 50
  • 70
  • https://stackoverflow.com/questions/8897749/php-array-assign-by-copying-value-or-by-reference?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Leszek P May 29 '18 at 13:22
  • 1
    Apparently, that second `$b = $a` doesn't remove the reference or something? If we unset `$b` before, then the results are as expected. https://3v4l.org/879up Yep, I was right: see ojar26's answer here: https://secure.php.net/manual/en/language.references.unset.php – Loek May 29 '18 at 13:24
  • 1
    `$b = $a` assigns the value `$a` points to into the slot `$b` (and `$a`) refers to. So now both `$b` and `$a` point to the same value (which they did before, so it's a noop essentially). Variables linked by reference is something other than object references. Think of it as: `$b = &$a` → make `$b` point to the slot `$a` points to; `$b = ...` → put `...` into the slot `$b` points to. – deceze May 29 '18 at 13:54
  • @deceze Thanks. So if I want to force $b to point to a new slot in memory (and be allocated again) - I need to destroy all existing references of $b with `unset($b)`. And no other way around, yes ? – Agnius Vasiliauskas May 29 '18 at 14:16
  • Yes, `unset` is the only way to break a reference IIRC. – deceze May 29 '18 at 14:17

0 Answers0