In PHP it’s possible to define variable variables, variables with names that are set and used dynamically.
Normal variables are set with statements like:
<?php
$fruit = 'apple';
?>
Variable variables are set by using two dollar signs in front of a normal variable‘s name:
<?php
$fruit = 'apple';
$$fruit = 'red';
?>
This results in two variables being defined: $fruit with the value ‘apple‘, and $apple with the value ‘red‘, which means that these two echo statements will produce the same results:
<php
$fruit = 'apple';
$$fruit = 'red';
echo "$fruit ${$fruit}";
echo "$fruit $apple";
?>
Associative arrays and foreach loops
Multiple variable variables can be created from associative arrays using a foreach loop:
<?php
$fruit = array('lime' => 'green',
'apple' => 'red',
'banana' => 'yellow');
foreach ($fruit as $key=>$value)
{
$$key = $value;
}
print_r($fruit);
echo "\nLime: {$lime}\n";
echo "\nApple: {$apple}\n";
echo "\nBanana: {$banana}\n";
?>
… resulting in:
Array
(
[lime] => green
[apple] => red
[banana] => yellow
)
Lime: green
Apple: red
Banana: yellow
Ambiguity
Keep in mind that when variable variables are used with arrays, there is an inherent ambiguity problem (see the PHP code examples below). If you write $$fruit[1], the parser needs to know if you meant:
Use ‘$fruit[1]‘ as the variable name, hence creating ‘$apple’ with a value of ‘red‘:
<?php
$fruit = array('lime',
'apple',
'banana');
$$fruit[1] = 'red';
?>
… or…
Assign ‘red‘ to the ‘[1]‘ index on ‘$$fruit’, hence creating an array ‘$apple’ with ‘red‘ in position ‘[1]‘:
<?php
$fruit = 'apple';
$$fruit[1] = 'red';
?>
The syntax for resolving this ambiguity is ${$fruit[1]} for the first case and ${$fruit}[1] for the second:
<?php
$fruit = array('lime',
'apple',
'banana');
${$fruit[1]} = 'red';
$fruit = 'apple';
${$fruit}[1] = 'red';
?>