Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Assignment by reference (`=&`) in PHP

Use `=&` to bind two names to the same variable contents. A write through either name is visible through the other for as long as both names remain bound.

Version: PHP 8.3; extension availability may vary

Syntax

$alias =& $source;
$alias = &$source; // Equivalent spacing

In PHP 8.3, reference assignment =& binds two names to the same variable contents: $alias =& $source and $alias = &$source mean the same thing. Neither name points to the other like a C pointer. Do not confuse =& with &=, which performs bitwise AND and assigns the result.

$copy = $source reads the current value without making $copy an alias of $source. If $copy is already an alias of another variable, = writes to those shared contents. With object assignment using =, both variables can identify the same object, but replacing the value of one variable does not by itself change the other.

On the right, use a variable, an array element, or a call to a function declared to return a variable by reference. A literal, a computed value, and a new expression are not valid reference sources. Binding to a function call that returns by value emits E_NOTICE and does not create an alias. Binding to an undefined variable creates it with the value null; initialize it first if that is not what you want.

$alias =& $other rebinds only $alias. unset($alias) removes just that name; any remaining aliases can still access the contents. By contrast, $alias = null writes null to the shared contents.

Copying an array with = can preserve references held by individual elements. If foreach ($items as &$value) visits at least one element, $value remains bound to the last element visited after the loop, even if break stops the loop before it reaches the end of the array. Use unset($value) immediately after the loop so a later write cannot accidentally change that element.

Examples

<?php
$source = 10;
$alias =& $source;
$copy = $source;

$alias = 20;
echo "$source $alias $copy\n";

$source = 30;
echo "$source $alias $copy\n";

unset($alias);
$alias = 40;
echo "$source $alias $copy\n";

Result

20 20 10
30 30 10
30 40 10

The first two lines show that writes through either bound name are visible through the other, while `$copy` stays at `10`. After `unset($alias)`, assigning `40` no longer changes `$source`.

Related lessons

  • PHP · Lesson 80 · Advanced · Version: 2

Sources