Variable Variables

La Lakshmi Priya Updated 29 Oct 2026
9 min read

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

  1. $fieldName holds the string "city".
  2. $$fieldName = "Chennai"; is evaluated in two steps:
    • PHP reads $fieldName and gets "city".
    • It then assigns "Chennai" to a variable named city — that is, $city.
  3. $city now exists, even though the code never wrote $city = directly.
  4. echo $city; prints Chennai.

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

ExpressionMeaning
${$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

  • stdClass is PHP's generic empty object, useful for simple data. Classes and objects are covered in the PHP OOP section.
  • $product->$field reads 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

AspectVariable VariablesArray
Where the data livesScattered across many separate variablesOne variable holding related values
Looping over all valuesRequires a separate list of namesBuilt in with foreach
Counting, sorting, filtering, JSON encodingNot possible directlycount(), ksort(), array_filter(), json_encode()
Passing to a functionMust pass each variable separatelyPass one array
Editor support (autocomplete, "find usages")Editors cannot know which variables existKeys are visible in the code
Risk of overwriting other variablesHighNone — 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 $$, ${}, or extract().
  • Use "{$var}" instead of the deprecated "${var}" inside strings.

Official reference: https://www.php.net/manual/en/language.variables.variable.php

0 Comments

Reviewed before they appear

No comments yet.

Data Mining
Introduction to Data Mining Data Mining Implementation Process Data Mining Architecture Data Mining Techniques KDD: Knowledge Discovery in Databases History of Data Mining Data Mining Tools Data Mining vs Machine Learning Facebook Data Mining Social Media Data Mining Methods Clustering in Data Mining Text Data Mining Bagging vs Boosting Data Mining vs Data Warehousing Social Media Data Mining Data Mining: Bayesian Classifiers Data Mining: World Wide Web Different Types of Clustering Bitcoin Mining and Blockchain Data Mining Orange Data Mining Data Mining vs Big Data Decision Tree Induction Educational Data Mining Data Mining in Healthcare Apriori Algorithm Data Integration in Data Mining Difference Between Data Mining and Text Mining Discretization in Data Mining Redundancy and Correlation in Data Mining Classification of Data Mining Systems Classification Algorithms in Data Mining Data Generalization in Data Mining Classification and Prediction in Data Mining Regression in Data Mining What Is an Outlier in Data Mining Data Cleaning in Data Mining Data Processing in Data Mining Data Mining Task Primitives Web Content Mining, Web Structure Mining, and Web Usage Mini Binning in Data Mining KDD vs. Data Mining Noise in Data Mining BIRCH in Data Mining Stemming in Data Mining Feature Transformation in Data Mining Visual and Audio Data Mining Class Comparison Methods in Data Mining Data Selection in Data Mining Tasks and Functionalities of Data Mining Ubiquitous and Invisible Data Mining Importance of Data Mining Data Quality in Data Mining Mining Frequent Patterns in Data Mining Data Warehouse and OLAP Technology for Data Mining Need for Data Mining Pattern Evaluation Methods in Data Mining Logarithms and Exponents in Complexity Analysis Time Series Clustering What is the C4.5 Algorithm and How Does It Work? Expanding Contractions in Text Mining Cosine Similarity in Data Mining Lazy Learning in Data Mining Neural Networks in Data Mining Building a Text Normalizer Shallow Parsing Data Pipeline Orchestration Big Data vs Small Data Myths of Data Mining Data Reduction in Data Mining Data Mining Models Difference Between Data Mining and Data Science Difference Between Data Mining and Statistics Difference Between Data Mining and Web Mining Difference Between Data Mining and Data Analysis Difference Between Business Intelligence and Data Mining Difference Between Data Mining and Data Visualization Data Mining vs Data Analytics Types of Data Mining Difference Between Data Profiling and Data Mining Predictive Analytics vs Data Mining Difference Between Data Mining and OLAP Descriptive and Predictive Data Mining Difference Between Spatial and Temporal Data Mining Difference Between Classification and Clustering in Data Min Hierarchical Clustering in Data Mining Density-Based Clustering in Data Mining What Is Aggregation in Data Mining?
Ask about this post
AI Ask about this post

Ask questions about Variable Variables and get answers drawn from it.

Signed-in readers only.