Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reference In Array

By True Async

<?php
$original = array("data" => "original value");

$element_reference = &$original["data"];
//unset($element_reference);

$copy = $original;
$copy["data"] = "value set in copy";
$copy["foo"] = "another value added in copy";

echo "Original(?): "; var_dump($original);
echo "Copy(?): "; var_dump($copy);

And what happens if we uncomment unset($r)?

In this code, the value of

$b[‘x’] depends on whether unset($r) is executed. In one case,

$b[‘x’] becomes 3; in the other, it remains 1. The important thing is not to mix them up.

Why?

Because $r = &$a[‘x’]; modifies the array by creating a hidden IS_REFERENCE wrapper. From that point on, copies of the array inherit that reference.

However, once the reference’s refcount drops to one, it is lazily dereferenced. After that, copies of the array behave as they normally would.

See Also

PHP Error Messages

PHP Features

Last updated: 11 October 2026