What is the meaning and usage of '=&' assignment operator in PHP?

The =& operator in PHP creates a reference assignment, where two variables point to the same data location in memory instead of copying the value. This is known as "assignment by reference" and helps avoid data redundancy by making both variables share the same underlying data.

Syntax

The syntax for reference assignment is −

<?php
    $variable1 = &$variable2;
?>

Basic Example

Here's how reference assignment works with simple variables −

<?php
    $my_val1 = 67;
    $my_val2 = &$my_val1;  // Reference assignment
    $my_val1 = 89;         // Changing the first variable
    
    echo "my_val1: " . $my_val1 . "<br>";
    echo "my_val2: " . $my_val2;
?>
my_val1: 89
my_val2: 89

Reference vs Copy Assignment

Let's compare reference assignment with regular copy assignment −

<?php
    // Copy assignment (default)
    $a = 10;
    $b = $a;        // Copy the value
    $a = 20;
    echo "Copy assignment - a: $a, b: $b<br>";
    
    // Reference assignment
    $x = 10;
    $y = &$x;       // Reference to the same memory location
    $x = 20;
    echo "Reference assignment - x: $x, y: $y";
?>
Copy assignment - a: 20, b: 10
Reference assignment - x: 20, y: 20

With Arrays and Objects

Reference assignment is particularly useful with arrays and objects −

<?php
    $original_array = array(1, 2, 3);
    $ref_array = &$original_array;
    
    $original_array[] = 4;  // Add element to original
    
    print_r($ref_array);    // Both arrays are updated
?>
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Key Points

  • Both variables point to the same memory location
  • Changes to either variable affect both
  • No data copying occurs, saving memory
  • Useful for large arrays or objects to avoid duplication

Conclusion

The =& operator creates a reference link between variables, making them share the same data. This prevents data duplication and ensures that changes to one variable are reflected in all referenced variables.

Updated on: 2026-03-15T09:00:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements