Questions And Answers

More Tutorials

PHP Assign by Reference

This is the first phase of referencing. Essentially when you assign by reference, you're allowing two variables to share the same value as such.

$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 assign by reference within the array() language construct. While not strictly being an assignment 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.
Assigning by reference is not only limited to variables and arrays, they are also present for functions and all "passby-reference" associations.

function incrementArray(&$arr) {
 foreach ($arr as &$val) {
function &getArray() {
 static $arr = [1, 2, 3];
 return $arr;


[2, 3, 4]

Assignment is key within the function definition as above. You can not pass an expression by reference, only a value/variable. Hence the instantiation of $a in bar().


In this page (written and validated by ) you learned about PHP Assign by Reference . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP by Reference.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.