PHP $ and $$ Variable

The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using $ symbol before $x value.

 

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.

 

Example:

<?php  

  $x = "xyz"; 
 
  $$x = 100;  

  echo $x."<br/>"; 
 
  echo $$x."<br/>"; 
 
  echo $abc;  

?>  

Output:
xyz
100
100

 

In the above example, we have assigned a value to the variable x as xyz. Value of reference variable $$x is assigned as 100.

 

Another Example: Now we have printed the values $x, $$x.

 

<?php  

	$x="Punjab";  

	$$x="Chandigarh"; 

	echo $x. "<br>";  

	echo $$x. "<br>";  

	echo "Capital of $x is " . $$x; 

?>
  
Output:

Punjab
Chandigarh
Capital of Punjab is Chandigarh

 

In the above example, we have assigned a value to the variable x as Punjab. Value of reference variable $$x is assigned as Chandigarh.

 

Another Example: 

<?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.