17 – Difference Between $ and $$ in PHP

Difference Between $ and $$ in PHP

This tutorial will focus on the difference between $ and $$ PHP To start with, let’s review first what is PHP Variables.

PHP Variable plays a vital role in PHP programming. It allows you to store information in computer memory.

To declare a PHP variable, it starts with a dollar sign($) like as shown in the syntax below

PHP Variable Syntax:

<?php

$variableName = "value";

?>

$$ Meaning in PHP (Double Dollar Variable)

The PHP $$ (double dollar) variable is a reference variable that stores the value which is accessible by using $ Symbol(Single Dollar) variable value

They call it sometimes as a variable variable name. Wherein the variable name can be set and used dynamically.

Below examples illustrate the use of $ and $$ in PHP

<?php

$myvar = "PHP";
echo $myvar;

?>

[su_box title=”Output Will Be:” radius=”7″ ]PHP[/su_box]

Here’s the $$ in PHP Example

<?php

$myvar = "PHP";
$myvar = "Programming!";
echo $myvar. '<br/> ';
echo $myvar. '<br/> ';
echo $PHP. '<br/> ';

?>

[su_box title=”Output Will Be:” radius=”7″ ]

PHP
Programming!
Programming!

[/su_box]

Another Complex Example of $$ in PHP

<?php

$myvar = "PHP";  
${$myvar}="Programming";  
  
${${$myvar}}="Is Fun!"; 
  
echo $myvar . "<br/>";  
echo $PHP . "<br/>";  
echo $Programming . "<br/>";  
  
echo ${${$myvar}}. "<br/>";  
  
?>

[su_box title=”Output Will Be:” radius=”7″ ]

PHP
Programming
Is Fun!
Is Fun!

[/su_box]

We will discuss what we have in the above code using PHP Double dollar and Dollar Variables

  1. First, we declare and initialize the variable.
  2. Then, reference the variable
  3. Next, we use the double reference variable
  4. Finally, we display the value of the variable.
  5. Lastly, we display a double reference.

Note:

If you have any questions about the $$ in PHP example, please feel to contact us or simply leave a comment below.

 

Leave a Comment