Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP References
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 operations 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.
Assign By Reference
You can create a reference by using the & operator. When you assign $b = &$a, both variables point to the same content −
<?php $var1 = 10; $var2 = &$var1; echo "var1: $var1, var2: $var2
"; $var2 = 20; echo "var1: $var1, var2: $var2
"; ?>
The output shows that changing one variable affects the other −
var1: 10, var2: 10 var1: 20, var2: 20
References in Foreach Loops
If you assign, pass, or return an undefined variable by reference, it will get created. When a value is assigned to a variable with references in a foreach statement, the references are modified too −
<?php
$arr = [1, 2, 3, 4, 5];
$ref = 0;
$i = &$ref;
foreach($arr as $i) {
echo $i * $i . "
";
}
echo "ref = " . $ref;
?>
The value of $ref stores the last element from the array −
1 4 9 16 25 ref = 5
Array Elements as References
Array elements can be references to individual variables. If an element is modified, the value of the original variable also changes −
<?php
$a = 10;
$b = 20;
$c = 30;
$arr = array(&$a, &$b, &$c);
for ($i = 0; $i < 3; $i++) {
$arr[$i]++;
}
echo "a: $a, b: $b, c: $c";
?>
The values of $a, $b, and $c get incremented through the array references −
a: 11, b: 21, c: 31
Conclusion
PHP references allow multiple variable names to point to the same content using the & operator. They are useful for avoiding data copying and creating aliases, but should be used carefully to prevent unexpected side effects.
