Home >Backend Development >PHP Tutorial >Change variables_PHP tutorial
Sometimes it is very convenient to use mutating variables. That is, a variable's name will be dynamically set and used. An ordinary variable would be declared using the following:
$a = "hello";
A mutator gets the value of a variable and treats it as the variable's name. In the above example, "hello" can be used by using the variable name plus two $, for example.
$$a = "world";
At this point, two variables are defined and stored in PHP's symbol tree; the content of $a is "hello", and the value of $hello is "world ". So the following statement:
echo "$a ${$a}";
produces the exact same output as:
echo "$a $hello";
They both output: " hello world”
To use mutating variables in an array, you have to solve an ambiguous problem. It is: if you write "$$a[1]", then the parser will need to know whether you want to use $a[1] as a variable or $$a as a variable, so that the index "[1]" might be Ambiguities will occur. The syntax to resolve this ambiguity is: "${$a[1]}" or use "${$a}[1]" (for the second case above).