Home >>PHP Tutorial >PHP $ and $$ Variables

PHP $ and $$ Variables

Difference Between $var and $$var in PHP

PHP $$var uses the value of the variable whose name is the value of $var. It means $$var is known as reference variable where as $var is normal variable. It allows you to have a "variable's variable" - the program can create the variable name the same way it can create any other string.

Var $and Var $$

1. For Example - PHP $ and PHP $$

<?php

$name="Rajeev";

$name="Sanjeev";

echo $name."<br/>";

echo $name."<br/>";

echo $Rajeev;
	
?>

Output
Rajeev
Sanjeev
Sanjeev

In the above example $name is just a variable with string value="Rajeev". $$name is reference variable .

$$name uses the value of the variable whose name is the value of $name.

echo $name print the value: Rajeev echo $$name print the value:Sanjeev \ value of this($name) variable is act as reference of second variable($$name).

echo $rajeev print the value :Sanjeev \ Here $Rajeev is also act as reference variable.

 Example - 2 

<?php

$x = "100";

$x = 200;

echo $x."<br/>";

echo $x."<br/>";

echo "$100";
	
?>

Output
100
200
200

In the Above Example

You first assign the value of a variable, ($x) as the name of another variable.

When you set $x to a value, it will replace that variable name with the value of the variable you provide.

variable $x hold value = 100.

$$x(reference variable) hold value = 200. now we want to print the value.

echo $x gives output:100

echo $$x gives output:200.

echo $100 gives value.200. because it also act as a reference variable for value = 200.


 Example 3.

<?php

$name="Rajeev";

${$name}="Sanjeev";

echo $name."<br/>";

echo ${$name}."<br/>";

echo "$Rajeev"."<br/>";
	
?>

Output Rajeev Sanjeev Sanjeev

 Example 4.

<?php
	
$name="Ravi";
	
${$name}="Ranjan";
	
${${$name}}="Rexx";
	
echo $name;
	
echo ${$name};
	
echo ${${$name}};
  
?>

Output
Ravi
Ranjan
Rexx

In the Above Example

variable $name hold value ="ravi"

variable ${ $name } hold value ="Ranjan" // it also declare like ${Ravi}.

variable ${$ {$name} } hold value ="Rexx" // it act as "variable's of variable of variable" reference.

echo $name show output:ravi

echo ${ $name } show output:Ranjan.

echo ${ $ {$name} } show output :Rexx


No Sidebar ads