Assign by Reference
suggest changeThis is the first use of references. When you assign by reference, two variables share the same value.
$foo = &$bar;
$foo and $bar are equal here. They do not point to one another. They point to the same place (the “value”).
You can also store references inside an array created with array(). That is not the same as assigning the array itself by reference.
$foo = 'hi';
$bar = array(1, 2);
$array = array(&$foo, &$bar[0]);
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.
References are not limited to variables and arrays. Functions can take parameters by reference and can return by reference.
function incrementArray(&$arr) {
foreach ($arr as &$val) {
$val++;
}
}
function &getArray() {
static $arr = [1, 2, 3];
return $arr;
}
incrementArray(getArray());
var_dump(getArray()); // prints an array [2, 3, 4]
The & belongs in the function definition, not at the call. You cannot pass an arbitrary expression by reference, only a variable. A function that returns by reference, as getArray() does, is allowed here. Calling incrementArray(getArray()) therefore updates the static array.