PHP References


Introduction

In PHP, References enable accessing the same variable content by different names. They are not like pointers in C/C++ as it is not possible to perform arithmetic oprations using them. In C/C++, they are actual memory addresses. In PHP in contrast, they are symbol table aliases. In PHP, variable name and variable content are different, so the same content can have different names. A reference variable is created by prefixing & sign to original variable. Hence $b=&$a will mean that $b is a referewnce variable of $a.

Assign By Reference

In following example, two variables refer to same value

Example

 Live Demo

<?php
$var1=10;
$var2=&$var1;
echo "$var1 $var2
"; $var2=20; echo "$var1 $var2
"; ?>

Output

Change in value of one will also be reflected in other

10 10
20 20

If you assign, pass, or return an undefined variable by reference, it will get created. Assigning a reference to a variable declared global inside a function, the reference will be visible only inside the function. When a value is assigned to a variable with references in a foreach statement, the references are modified too.

Example

 Live Demo

<?php
$arr=[1,2,3,4,5];
$i=&$ref;
foreach($arr as $i)
echo $i*$i, "
"; echo "ref = ". $ref; ?>

Output

Value of $ref stores that of last element in array

1
4
9
16
25
ref = 5

In following example, array element are references to individual variables declared before array initialization. If element is modified, value of variable also changes

Example

 Live Demo

<?php
$a = 10;
$b = 20;
$c=30;
$arr = array(&$a, &$b, &$c);
for ($i=0; $i<3; $i++)
$arr[$i]++;
echo "$a $b $c";
?>

Output

Values of $a, $b and $c also get incremented

11 21 31

Updated on: 18-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements