Variable Variables
What Are Variable Variables?
In simple terms: A variable variable is a variable whose name is stored in another variable. Instead of writing the variable name directly in your code, you decide the name while the program runs.
Technically: PHP allows an expression to supply a variable's name. Writing $$name tells PHP: "take the value of $name, and use that value as the name of the variable to access." This is a form of dynamic variable access.
Why This Feature Exists
Normally, variable names are fixed when you write code: $color, $price. Variable variables let code choose which variable to use based on data — a configuration key, a field name, or a loop value. PHP supports this because it is a dynamic language where variable names are stored internally as strings in a symbol table.
In practice, variable variables are rarely the best tool. Arrays almost always solve the same problems more clearly and more safely. This lesson explains how variable variables work so you can understand them in existing code, recognize their risks, and know the better alternatives.
Basic Syntax
$$variableName
The first $ belongs to the variable being accessed; $variableName supplies its name.
Example
<?php
$fieldName = "city";
$$fieldName = "Chennai";
echo $city;
Output
Chennai
Step-by-Step Explanation
$fieldNameholds the string"city".$$fieldName = "Chennai";is evaluated in two steps:- PHP reads
$fieldNameand gets"city". - It then assigns
"Chennai"to a variable namedcity— that is,$city.
- PHP reads
$citynow exists, even though the code never wrote$city =directly.echo $city;printsChennai.
Both of these lines access the same variable:
echo $city;
echo $$fieldName;
The Curly-Brace Form: ${...}
Curly braces make the dynamic part explicit and allow any expression to produce the name.
Example
<?php
$prefix = "user";
${$prefix . "Name"} = "Arjun";
${$prefix . "Email"} = "arjun@example.com";
echo $userName . "\n";
echo $userEmail . "\n";
Output
Arjun
arjun@example.com
How It Works
${$prefix . "Name"}first evaluates$prefix . "Name", which is"userName".- That string becomes the variable name, so the assignment creates
$userName.
The braces are required here. Without them, $$prefix . "Name" would mean "the variable named by $prefix" (that is, $user) concatenated with "Name".
Variable Variables and Arrays
When a variable variable is combined with array access, the meaning depends on braces.
Example
<?php
$names = ["first", "second"];
$first = "Value of \$first";
$list = "items";
$items = ["apple", "banana"];
// Use an array element as the variable name
echo ${$names[0]} . "\n";
// Access an element of the variable named by $list
echo ${$list}[1] . "\n";
echo $$list[1] . "\n";
Output
Value of $first
banana
banana
How PHP Reads These Expressions
| Expression | Meaning |
|---|---|
${$names[0]} | Evaluate $names[0] → "first", then access $first |
${$list}[1] | Access the variable named by $list ($items), then take element [1] |
$$list[1] | Same as ${$list}[1] in PHP 7 and later |
Version note: PHP 7.0 introduced uniform variable syntax, which evaluates expressions strictly from left to right. In PHP 5,
$$list[1]meant${$list[1]}— the opposite. Old code relying on PHP 5 behavior may break silently. Always use curly braces to make your intention explicit.
Dynamic Property Names on Objects
The same idea applies to object properties: a variable can supply the property name.
Example
<?php
$product = new stdClass();
$product->name = "Desk Lamp";
$product->price = 1299;
$product->stock = 40;
$fieldsToShow = ["name", "price"];
foreach ($fieldsToShow as $field) {
echo "$field: " . $product->$field . "\n";
}
$column = "stock";
echo "Stock: " . $product->{$column} . "\n";
Output
name: Desk Lamp
price: 1299
Stock: 40
How It Works
stdClassis PHP's generic empty object, useful for simple data. Classes and objects are covered in the PHP OOP section.$product->$fieldreads the property whose name is the value of$field. On the first loop iteration, that is$product->name.$product->{$column}is the braced form; braces allow expressions such as$product->{"get" . $suffix}.
This form of dynamic access is common in real applications — for example, in code that maps database columns to object properties or builds tables from a list of selected fields. It is generally more acceptable than variable variables, because the dynamic name is limited to properties of one known object.
Restrictions
Superglobals and $this
Inside functions and class methods, variable variables cannot be used to access superglobal arrays ($_GET, $_POST, $_SERVER, and so on) or $this.
<?php
function readInput()
{
$source = "_GET";
return $$source; // does not access $_GET
}
Inside the function, $$source looks for a local variable named $_GET, which does not exist, so you get an "Undefined variable" warning. Superglobals are resolved specially when the code is compiled, and that does not happen for dynamically built names.
Scope Still Applies
A variable variable follows normal scope rules. Inside a function, $$name creates or reads a variable in that function's local scope, not in the global scope.
<?php
function setVariable()
{
$name = "message";
$$name = "Hello";
}
setVariable();
echo $message ?? "Not set";
Output
Not set
$message was created inside the function and destroyed when the function returned.
Not to Be Confused With "${var}" in Strings
PHP strings also support a ${...} syntax for interpolation:
<?php
$name = "Asha";
echo "Hello ${name}"; // deprecated since PHP 8.2
echo "Hello {$name}"; // recommended
This is a different feature that happens to look similar. The "${var}" and "${expr}" interpolation forms are deprecated since PHP 8.2 and produce a deprecation notice. Use "{$name}" or "$name" instead. Variable variables written in normal code (${$name}, outside strings) are not deprecated.
Why Arrays Are Usually Better
The Same Task With Variable Variables
<?php
$fields = ["name", "email", "phone"];
foreach ($fields as $field) {
$$field = "";
}
$name = "Kavya";
$email = "kavya@example.com";
foreach ($fields as $field) {
echo "$field: " . $$field . "\n";
}
The Same Task With an Array
<?php
$contact = [
"name" => "",
"email" => "",
"phone" => "",
];
$contact["name"] = "Kavya";
$contact["email"] = "kavya@example.com";
foreach ($contact as $field => $value) {
echo "$field: $value\n";
}
Output (both versions)
name: Kavya
email: kavya@example.com
phone:
Why the Array Version Is Better
| Aspect | Variable Variables | Array |
|---|---|---|
| Where the data lives | Scattered across many separate variables | One variable holding related values |
| Looping over all values | Requires a separate list of names | Built in with foreach |
| Counting, sorting, filtering, JSON encoding | Not possible directly | count(), ksort(), array_filter(), json_encode() |
| Passing to a function | Must pass each variable separately | Pass one array |
| Editor support (autocomplete, "find usages") | Editors cannot know which variables exist | Keys are visible in the code |
| Risk of overwriting other variables | High | None — keys are isolated inside the array |
Whenever you find yourself building variable names like $item1, $item2, $item3 or $$field, use an array instead.
Security Risk: Variable Variables With User Input
Using external input as a variable name is dangerous, because the user chooses which variable is created or overwritten.
Vulnerable Example
<?php
$isAdmin = false;
// Imagine $_GET contains ['name' => 'Ravi', 'isAdmin' => '1']
foreach ($_GET as $key => $value) {
$$key = $value;
}
if ($isAdmin) {
echo "Welcome to the admin panel";
}
A visitor requesting profile.php?name=Ravi&isAdmin=1 overwrites $isAdmin with "1", which is truthy, and gains access to the admin panel.
Why This Happens
The loop turns every query-string key into a variable. Any variable in the current scope — permissions flags, database credentials, file paths — can be overwritten by adding a parameter to the URL. Early PHP versions had a setting called register_globals that did exactly this automatically; it caused so many security holes that it was removed in PHP 5.4.
The built-in extract() function, which creates variables from array keys, has the same risk when used on user input.
Safe Approach
Keep input in an array and read only the keys you expect:
<?php
$name = $_GET['name'] ?? '';
$isAdmin = false; // determined by your login system, never by the request
Warning: Never use variable variables or
extract()with data from$_GET,$_POST,$_COOKIE,$_REQUEST, JSON request bodies, or any other external source.
Where Variable Variables Appear in Practice
You will mostly see this pattern in:
- Simple template systems, which turn an array of data into local variables before including a template (usually with
extract()on trusted, developer-controlled data). - Legacy code, written before arrays and objects were used consistently.
- Dynamic property and method access on objects (
$object->$property,$object->$method()), which is more common and more justifiable.
A related function, compact(), does the reverse of extract(): it builds an array from existing variables by name.
<?php
$title = "Dashboard";
$userName = "Meena";
$data = compact('title', 'userName');
print_r($data);
Output
Array
(
[title] => Dashboard
[userName] => Meena
)
compact() is safe in this form because the variable names are fixed in your code.
Common Mistakes
Forgetting Braces With Expressions
Problem: $$prefix . "Name" instead of ${$prefix . "Name"}.
Effect: PHP reads the variable named by $prefix, then concatenates "Name" to its value.
Fix: Wrap any expression that builds a name in ${ }.
Relying on PHP 5 Array Behavior
Problem: $$names[0] written for PHP 5, where it meant ${$names[0]}.
Effect: In PHP 7+, it accesses the variable named by $names, then index [0].
Fix: Use explicit braces: ${$names[0]} or ${$names}[0].
Creating Variables From User Input
Problem: $$key = $value for request data, or extract($_POST).
Effect: Attackers can overwrite any variable in scope.
Fix: Read expected keys explicitly from the input array.
Using Variable Variables Instead of Arrays
Problem: $product1, $product2, ${"product$i"}.
Effect: Data cannot be counted, sorted, passed, or encoded easily.
Fix: Use $products[$i].
Best Practices
- Prefer arrays (or objects) whenever names would be built dynamically.
- Use dynamic property access on known objects only with names that come from your own code, not from users.
- Always use curly braces to make dynamic names unambiguous.
- Never create variables from external input with
$$,${}, orextract(). - Use
"{$var}"instead of the deprecated"${var}"inside strings.
Official reference: https://www.php.net/manual/en/language.variables.variable.php