Assignment by Reference Operator in PHP

Kevin Amayi Jan 30, 2023
  1. Use the =& Operator to Create a Non-Existent Variable in PHP
  2. Use the =& Operator to Point More Than One Variable to the Same Value (Memory Location) in PHP
  3. Use the =& Operator to Link More Than One Variable in PHP
  4. Use the =& Operator to Unlink More Than One Variable in PHP
Assignment by Reference Operator in PHP

This article demonstrates creating a non-existent variable, pointing more than one variable to the same value, linking multiple variables, and unlinking multiple variables using the assignment by reference or the =& operator or in PHP.

Use the =& Operator to Create a Non-Existent Variable in PHP

We will create an array and use the assignment by reference operator to create an array variable without initially declaring the variable.

<?php
    $test = array();
    $test1 =& $test['z'];
    var_dump($test);
?>

Output:

array(1) {
	["z"]=>
	&NULL
}

Use the =& Operator to Point More Than One Variable to the Same Value (Memory Location) in PHP

We will create a variable, assign a value to it, and then use the assignment by reference operator to make other variables point to the same memory location as the first variable.

<?php
    $firstValue=100;
    $secondValue =& $firstValue;
    echo "First Value=".$firstValue."<br>";
    echo "Second Value=". $secondValue."<br>";
    $firstValue = 45000;
    echo "After changing the value of firstValue, secondValue will reflect the firstValue  because of =&","<br>";
    echo "First Value=". $firstValue."<br>";
    echo "Second Value=". $secondValue;
?>

Output:

First Value=100
Second Value=100

After changing the value of firstValue, secondValue will reflect the firstValue  because of =&

First Value=45000
Second Value=45000

We will create a variable, assign a value to it, and then use the assignment by reference operator to link other variables to the initial variable. They all point to the initial variable value.

<?php
    $second = 50;
    $first =& $second;
    $third =& $second;
    $fourth =& $first;
    $fifth =& $third;

    // $first, $second, $third, $fourth, and $fifth now all point to the same data, interchangeably

    //should print 50
    echo $fifth;
?>

Output:

50

We will create two variables and assign values to them. Then use the assignment by reference operator to link and unlink other variables.

The variables point to different values.

<?php
    $second = 50;
    $sixth = 70;
    $first =& $second;
    $third =& $second;
    $fourth =& $first;
    $fifth =& $third;

    // $first, $second, $third, $fourth, and $fifth now all point to the same data, interchangeably

    //unlink $fourth from our link, now $fourth is linked to $sixth and not $third
    $fourth = $sixth;

    echo $fourth;
?>

Output:

70

Related Article - PHP Operator