Variable variables: Differences between $var and $$var in PHP
The $$var notation, also known as variable variables, introduces a dynamic approach to variable names in PHP.
Table of Contents
PHP, a widely-used programming language for web development, offers various features and constructs to manipulate variables. Two commonly used variable-related constructs in PHP are $var
and $$var
(variable variables). While they might seem similar at first glance, they have distinct differences and purposes. In this article, we will explore the dissimilarities between $var
and $$var
in PHP.
$var
The $var notation is the standard way of declaring and accessing variables in PHP. It is used to assign a value to a variable and retrieve the stored value later in the code. For example:
$name = "John";
echo $name; // Output: John
In the above example, $name
is a variable that stores the value “John.” The echo
statement retrieves the value of $name
and prints it to the output.
$$var (variable variables)
The $$var notation, also known as variable variables, introduces a dynamic approach to variable names in PHP. It allows you to create variables with names based on the value of another variable. Here’s an example:
$var = "name";
$$var = "John";
echo $name; // Output: John
In this case, $var contains the value “name.” By prefixing another dollar sign to the $var
variable, we create a new variable with the name “name.” Hence, the line $$var = “John”; dynamically creates a variable named $name
and assigns it the value “John.” The subsequent echo statement retrieves the value $name
and prints it to the output.
With $var
, you assign a value to the variable directly. For example, $name
= “John”; assigns the value “John” to the $name variable. Conversely, $$var
assigns a value to a variable based on the value of another variable. This dynamic assignment allows for more flexibility in naming variables.
One crucial distinction between $var
and $$var
is the level of indirection. While $var
provides direct access to the variable and its value, $$var
(variable variables) adds an additional level of indirection. It uses one variable’s value to determine the name of another variable and then accesses the value stored in that second variable.
In conclusion, $var
and $$var
(variable variables) are two distinct constructs in PHP with different purposes. $var
is the standard way of declaring and accessing variables, while $$var
allows for dynamic variable naming based on the value of another variable.