Variable Variables

La Lakshmi Priya Updated 30 Oct 2026
9 min read ·Lesson 202 of 209

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.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions
Ask about this post
AI Ask about this post

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

Signed-in readers only.