Advanced Variables and Using Them by Reference in PHP

PHP

Variables by Reference

Variables can also hold their value as a reference to another value. This means, a variable simply points to another variable. So whatever value the other variable holds, the reference variable also holds the same. For reference assignment we use an ampersand sign (&) after the equals to sign (=) while assigning a variable.

Example:

<?php
$var1 = "Ashish";
$var2 =& $var1;
$var1 = "Kathmandu";
echo $var1;
?>
Output:
Kathmandu
Notes:

  • See how the updated value of $var1 is printed when we output $var2.
  • If we hadn’t used the ampersand sign, then $var1 would hold the value “Ashish” till the end.
  • If we unset the value of $var1, $var2 will still hold the latest value.

Using Reference Variables in Functions

We can pass in variables in PHP as arguements. When we use reference variables, they are passed and updated by the function. To pass a variable by reference, place the ampersand sign (&)in front of the arguments passed in a function.

Example:

<?php
function refvar(&$a){
$a = $a + 5;
}
$value = 5;
refvar($value);
echo $value;
?>
Output:
10
Notes:

  • See how the value of the variable $value is updated by the function since it is passed by reference.
  • $var and $a points at the same thing.

Variable Variables

There’s an interesting way to set variables in PHP. A variable value can be another variable name. So, you will be using variable variables. Two $ signs are used for such purpose. This is used when we do not know the name of the variable. It sounds complicated, so here’s an example:

<?php
$var = "name";
$name = "Ashish";
echo $$var;
?>
Output:
Ashish
Note:

  • There are two $ (dollar) signs.
  • $var = name, so $$var = $name and $name happens to hold the value “Ashish”.

The same “Variable Variables” can also be used in arrays. But in arrays it can be confusing when we use two dollar signs. Like when we use $$name[0], the array position [0] makes it confusing and we might. Should we take the position of the array first or the $$variable first. For this issue, we can use curly braces to separate which comes first, just like in maths.

Example:

<?php
$var[0] = "name";
$name[0]="Ashish";
var_dump (${$var[0]});
?>
Output:
Array ( [0] => Ashish )