Variable Variables
PHP allows you to use the value of one variable as the name of another. This feature is called a variable variable, written with a double dollar sign: $$name. It is one of the more exotic corners of the language — rarely necessary, occasionally clever, and easy to abuse into unreadable code. Understanding it is useful even if you end up writing an array instead.
How $$ works
$$name means "take the string currently stored in $name, and use it as the name of another variable." The extra $ is what triggers this indirection.
Building a variable name from another variable
<?php $field = "color"; $$field = "blue"; // this creates a new variable called $color echo $color; // blue echo $$field; // blue - same variable, accessed indirectly
blue blue
Braces resolve ambiguity
When combining variable variables with array access or object
properties, use curly braces to make it clear which part is being
dereferenced first: ${$field} vs $$field behave the same for a
plain variable, but braces become essential once you add [...] or
-> to the expression.
Clarifying evaluation order with braces
<?php
$key = "status";
$status = "active";
echo ${$key}; // active - explicit form
echo "\n";
echo ${$key}[0]; // 'a' - first character of $statusactive a
A realistic (rare) use case
One legitimate scenario is dynamically picking from a small, known set of variables based on external input, such as generating several related report variables from a template.
Selecting one of several named totals
<?php
$mondaySales = 1200;
$tuesdaySales = 900;
$wednesdaySales = 1450;
function totalFor(string $day): int {
$varName = strtolower($day) . "Sales";
return $$varName ?? 0;
}
echo totalFor("Tuesday");900
The same idea with an array — almost always the better choice
<?php
$sales = [
"monday" => 1200,
"tuesday" => 900,
"wednesday" => 1450,
];
function totalFor(array $sales, string $day): int {
return $sales[strtolower($day)] ?? 0;
}
echo totalFor($sales, "Tuesday");900
Why it is usually a code smell
Static analysis tools and IDEs cannot trace
$$varback to a real variable name, so "find usages" and refactoring tools break silently.There is no way to
unset()or iterate over a group of variable variables the way you can loop over an array withforeach.Typos in the source string silently create a new, unrelated variable instead of raising an error.
Arrays (or objects) give you the same dynamic-key behaviour plus iteration, counting, and safe existence checks via
isset()/array_key_exists().