PHP variable Variables

In PHP, variable variables allow you to use the value of one variable as the name of another variable. This is achieved by prefixing a variable with two dollar signs ($$). This feature provides dynamic variable naming capabilities.

Syntax

The syntax for variable variables uses double dollar signs ?

$$variable_name = value;

Basic Example

Here's how variable variables work with string values ?

<?php
$var1 = "xyz"; // normal variable
$$var1 = "abcd"; // variable variable - creates $xyz = "abcd"

echo $var1 . "<br>";
echo $$var1 . "<br>";
echo $xyz . "<br>"; // same as $$var1
?>
xyz
abcd
abcd

In this example, $$var1 creates a new variable $xyz because the value of $var1 is "xyz".

Limitations with Numeric Values

Variable variables cannot use numeric values as variable names because PHP variable names must start with a letter or underscore ?

<?php
$var1 = 100;
$$var1 = 200; // This creates ${100} internally

echo $var1 . "<br>";
echo $$var1 . "<br>";
// echo $100; // This would cause a parse error
?>
100
200

Using with Array Elements

You can create variable variables using array elements by wrapping them in curly braces ?

<?php
$var1 = array("aa", "bb");
${$var1[0]} = 10; // creates $aa = 10

echo $var1[0] . "<br>";
echo $aa . "<br>";
echo ${$var1[0]} . "<br>";
?>
aa
10
10

Variable Property Names

Variable variables also work with object properties using curly brace syntax ?

<?php
class Branches {
    public $Architecture = "Available";
    public $ugCourses = array("CSE", "MECH", "CIVIL");
}

$obj = new Branches();
$property = "Architecture";
$courses = "ugCourses";

echo $obj->{$property} . "<br>";
echo $obj->{$courses}[0] . "<br>";
?>
Available
CSE

Conclusion

Variable variables provide flexibility for dynamic programming in PHP. Use them with string values for variable names, wrap array elements in curly braces, and apply the same concept to object properties for dynamic access.

Updated on: 2026-03-15T09:20:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements