2

This code

<?php

$a = 10;
$arr1 = array(&$a);

$arr1[0] = 20;
echo $a; echo "\n";

$arr2 = $arr1;
$arr2[0] = 30;

echo $a;

produces

20
30

Obviously reference array members are "preserved", which can lead, for example, to some interesting/strange behavior, like

<?php

function f($arr) {
    $arr[0] = 20;
}

$val = 10;
$a = array(&$val);

f($a);

echo $a[0];

?>

outputting

20

My question is: what is it for, where is it documented (except for a user comment at http://www.php.net/manual/en/language.types.array.php#50036) and the Zend Engine source code itself?

1 Answer 1

3

PHP's assignment by reference behavior is documented on the manual page "PHP: What References Do". You'll find a paragraph on array value references there, too, starting with:

While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add.

The page also explains your why your first code behaves like it does:

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

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

3 Comments

That should just be on the array's page too :).
@mlvljr: If you think so you can file a documentation bug: bugs.php.net/report.php
@nikic Posiibly, anyway, I've left a note at the array page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.