PHP variable variables allow you to create and access variables dynamically by using the value of another variable as the variable name.
At first glance, this feature can look a little strange. You are basically asking PHP to use one variable to decide the name of another variable. It feels like PHP is playing a small naming trick behind the scenes. Once you understand how it works, the syntax becomes simple.
This article explains PHP variable variables, how the $$ syntax works, how to use curly braces for clarity, and situations where this feature is useful or should be avoided.
What are variable variables in PHP?
A variable variable is a PHP variable whose name is stored inside another variable.
Normally, you create a variable by directly writing its name:
<?php
$name = "John";
echo $name;
?>
In this example, PHP knows that $name is the variable to read.
With variable variables, another variable contains the name of the variable that you want to access:
<?php
$variableName = "name";
$name = "John";
echo $$variableName;
?>
Output:
John
Here is what happens internally:
$variableNamecontains the text"name".$$variableNamebecomes$name.- PHP reads the value stored in
$name.
So the double dollar sign tells PHP: “Use the value of this variable as another variable’s name.”
Basic syntax of PHP variable variables
The syntax is:
$variable = "anotherVariable";
$$variable = "value";
For example:
<?php
$fruitName = "apple";
$$fruitName = "Red";
echo $apple;
?>
Output:
Red
In this example, PHP creates a variable called $apple because the value of $fruitName is "apple".
The above example works, but it also shows why variable variables can be confusing. The variable $apple does not appear anywhere directly in the code. Someone reading the code has to mentally follow the value of $fruitName to know what variable is being created.
Using curly braces with variable variables
When variable names are combined with additional text, curly braces help PHP understand exactly which part should be treated as the variable name.
Consider this example:
<?php
$name = "user";
$user = "John";
echo $$name . "_name";
?>
The intention may be to access a variable named $user and then append _name. However, PHP interprets this differently because the variable name ends at $name.
Curly braces make the variable variable boundary clear:
<?php
$name = "user";
$user = "John";
echo ${$name} . "_name";
?>
Output:
John_name
The syntax ${$name} tells PHP to first resolve $name, then use its value as the variable name.
Curly braces are especially useful when working with longer variable names or when combining variable variables with strings.
Creating multiple variables dynamically
One common use case for variable variables is when values need to be mapped dynamically to variable names.
For example, imagine receiving configuration values:
<?php
$settings = [
"siteName" => "PHPpot",
"language" => "PHP",
"version" => "8.2"
];
foreach ($settings as $key => $value) {
$$key = $value;
}
echo $siteName;
echo "<br>";
echo $language;
echo "<br>";
echo $version;
?>
Output:
PHPpot
PHP
8.2
During the loop, PHP creates these variables dynamically:
$siteName$language$version
This approach may look convenient, but it should be used carefully. In many modern PHP applications, an associative array or an object is usually a clearer choice.
Variable variables with arrays
Variable variables can also be used with arrays, but the syntax needs attention.
For example:
<?php
$arrayName = "users";
$users = [
"John",
"Mary"
];
echo ${$arrayName}[0];
?>
Output:
John
The curly braces are important here. Without them, PHP may not interpret the array access the way you expect.
The expression:
${$arrayName}[0]
is evaluated as:
$users[0]
Variable variables work with arrays, but if your data is already structured as an array, directly accessing the array is usually easier to understand.
Variable variables with objects
Variable variables can also be used when working with object properties. However, it is important to understand that variable variables create dynamic variable names, not dynamic property names.
For example, you can dynamically decide which variable contains an object:
<?php
$className = "user";
$user = new stdClass();
$user->name = "John";
echo ${$className}->name;
?>
Output:
John
Here, PHP first resolves ${$className} to $user, then accesses the name property.
For dynamic object properties, a better approach is usually to use normal object access with a variable property name:
<?php
$user = new stdClass();
$user->name = "John";
$property = "name";
echo $user->{$property};
?>
This is easier to read because the object remains the main structure, and only the property name changes dynamically.
When are PHP variable variables useful?
Variable variables are not something you will use every day in PHP development. In most cases, arrays, objects, or configuration classes provide a clearer solution.
However, there are situations where variable variables can be useful:
- Dynamic form processing: When field names are generated dynamically and need to map to existing variables.
- Template or report generation: When placeholders need to be resolved from dynamically named values.
- Legacy PHP applications: Older codebases sometimes use variable variables to handle dynamic data structures.
- Learning PHP internals: Understanding this feature helps you understand how PHP resolves variable names.
For new applications, consider whether an array or object would express the same idea more clearly before using $$.
Variable variables vs arrays
A common question is: “If I can create variables dynamically, why not just use an array?”
In most cases, arrays are the better choice.
Compare these two approaches:
Using variable variables
<?php
$color = "red";
$$color = "#ff0000";
echo $red;
?>
Using an array
<?php
$colors = [
"red" => "#ff0000"
];
echo $colors["red"];
?>
The array version has some advantages:
- The data structure is visible in one place.
- Values can be passed around easily.
- Debugging is simpler.
- There is less chance of accidentally overwriting existing variables.
A good rule is: use variable variables when they solve a real problem, not just because PHP allows it.
Common mistakes when using variable variables
Variable variables are simple once understood, but a few mistakes can make the code difficult to debug.
1. Forgetting that the variable name comes from the value
A frequent mistake is assuming that the variable name comes from the original variable name instead of its value.
<?php
$name = "city";
$$name = "London";
echo $city;
?>
Output:
London
PHP does not create a variable called $name. It creates a variable called $city because the value stored in $name is "city".
2. Creating variables that overwrite existing values
Since variable variables create variables dynamically, they can accidentally replace existing variables.
<?php
$message = "Original message";
$variableName = "message";
$$variableName = "Updated message";
echo $message;
?>
Output:
Updated message
The original value was overwritten because $$variableName became $message.
This is one reason why dynamically creating variables from external input is risky.
3. Using user input directly as a variable name
Avoid creating variable names directly from request data such as $_GET, $_POST, or $_REQUEST.
For example, avoid patterns like:
<?php
$$ _POST["field"] = "value";
?>
Apart from security concerns, this makes the application behaviour difficult to predict. An unexpected variable name could overwrite important values in your script.
If dynamic input needs to be stored, use an array with controlled keys instead:
<?php
$data = [];
$data[$_POST["field"]] = "value";
?>
Arrays keep dynamic data grouped together and avoid polluting the variable scope.
Debugging variable variables
When debugging code that uses variable variables, var_dump() is often more helpful than echo.
<?php
$variableName = "username";
$username = "John";
var_dump($variableName);
var_dump($$variableName);
?>
Output:
string(8) "username"
string(4) "John"
This helps confirm both parts of the process:
- The first variable contains the expected variable name.
- The dynamically accessed variable contains the expected value.
When debugging complex code, remember that $$variableName is simply PHP resolving one variable name from another variable’s value.
Alternatives to variable variables
Although PHP supports variable variables, modern PHP applications usually solve the same problems using more structured approaches.
Use arrays for dynamic values
Associative arrays are the most common replacement for variable variables.
<?php
$config = [
"database" => "mysql",
"environment" => "production"
];
echo $config["database"];
?>
The key name is dynamic, but the data remains grouped and easy to manage.
Use objects for related data
When values have behaviour or belong together, objects provide a cleaner design.
<?php
class User
{
public string $name;
public string $role;
}
$user = new User();
$user->name = "John";
$user->role = "Admin";
echo $user->name;
?>
Objects make the structure of your data clearer and easier to maintain as an application grows.
Use variable array keys instead of variable names
If the goal is to access values dynamically, array keys usually provide the same flexibility with fewer surprises.
<?php
$field = "email";
$user = [
"email" => "john@example.com"
];
echo $user[$field];
?>
This is often the pattern developers actually need when they first discover variable variables.
PHP variable variables and superglobals
PHP also allows variable variables with superglobal arrays, but this should be handled carefully.
For example, PHP has a feature called variable variables in its official documentation, but it does not mean every dynamic naming problem should be solved with $$.
Older PHP applications sometimes used patterns similar to extract() to convert array keys into variables:
<?php
$data = [
"title" => "PHP Variables"
];
extract($data);
echo $title;
?>
While extract() can be useful in limited situations, it can overwrite existing variables if not used carefully. The PHP manual recommends controlling how variables are extracted.
For application code, explicitly accessing array values is usually safer and easier to understand.
Frequently asked questions
What does $$ mean in PHP?
In PHP, $$ creates a variable variable. The value of the first variable is used as the name of another variable.
<?php
$name = "language";
$language = "PHP";
echo $$name;
?>
Output:
PHP
Are PHP variable variables recommended?
Variable variables are supported by PHP, but they are not the preferred choice for most modern applications. Arrays and objects usually make code easier to read and maintain.
Can variable variables create functions dynamically?
No. Variable variables work with variables. They do not create dynamic function names using the $$ syntax.
If you need dynamic function calls, PHP provides other features such as variable functions.
Conclusion
PHP variable variables provide a way to create and access variables dynamically using the $$ syntax. They can be useful in specific situations, especially when working with legacy code or dynamic naming requirements.
However, for most new PHP development, arrays and objects are usually clearer choices. They make your data structure visible and help other developers understand the code without having to follow a chain of dynamically generated names.
The $$ syntax is a useful tool to understand, but like many powerful language features, it works best when used with a clear reason.
Dear Vincy,
This is a the best article on this topic.
Thank you Tso-chuan Chou