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


Instead of copying the data from one variable to another one, the changes made to an array or object can be made to another using the ‘=&’ operator. This is known as the ‘assignment by reference’ method, which means both the values or objects will point to the same data, and no copies of the data are made. This way, data redundancy is avoided.

Example

 Live Demo

<?php
   $my_val1 = 67;
   $my_val2 = &$my_val1;
   $my_val1 = 89;
   print "The value is : ";
   print "$my_val2";
?>

Output

The value is : 89

Inside the <php> tags, two values are declared wherein the second value is the assignment by reference of the first value. Next, the value of the first variable is changed and the second value is displayed. It displays the most recently updated value of the first object. This means the changes made to the first variable have reflected in the second variable without making any copies.

Updated on: 01-Jul-2020

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements