What is the difference between $ and $$ variables in PHP?

To name a variable in PHP, the normal thing to do is:

$name = "variable";

But it is possible to use the dollar sign () twice or even more to helps us reference one variable value as the name of another. So when you try to make the name of a particular variable dynamically become the value of another variable, you do what is known as variable variable naming.

For instance, in the code below, two variables have been given the name no. The PHP engine will see $no as named no with value "yes", and will see the second $$no as named yes with the value be.

$no = "yes";
// To reference the above variable
// I can do
$$no = "be";

Code

<?php
$ba = "b";
$bal = "ba";
$bald = "bal";
$balder = "bald";
$b = "balder";
echo $b ."<br>"; //Returns balder
echo $$b ."<br>"; //Returns bald
?>

Variables and variable variable names in arrays

There can be some ambiguity when you first use variable variable naming.

For variable variables to be used successfully with arrays, one has to save the PHP engine from the problem of having to take a probable wrong decision because of the vagueness of the statement.

This means if you have to use $$array_g[1] for an array, say array_g, then the PHP parser engine needs to know what you really mean. Do you mean to use $array_g[1] as a variable? Or, do you want $$array_g to be the variable and then the [1] to be the index from that variable?

The simple hack to solve this problem is to use the syntax below.

${$array_g[1]} 
/*for the first case where you want to use $$array_g[1] as variable*/

${$array_g}[1] 
/*for the second where you want to use array $$array_g and then the index [1]

Code

Look at the code below, try to go through it and also practice to understand better.

<?php
// We can use this variables ...
$dayTypes = array("first", "second", "final");
$first_day = "Introduction";
$second_day = "Workshop";
$final_day = "Closure";
//And this loop...
foreach($dayTypes as $type)
print ${"${type}_day"} . "<br>";
echo "********<br>";
// To display same thing as this code here
print $first_day."<br>".$second_day."<br>".
$final_day;
/* The catch here is that the
first code is quite dynamic unlike the second*/
?>

You can use this concept in ways that suit you to add cool features to your code and explore more code while trying to solve difficult problems.

Free Resources