This question already has an answer here:
I am trying to learn php, and I saw this in a foreach loop what does it mean? I understand &$var which its a direct reference to the memory address of the object. But what does $$var means? what is it exactly?
This is the example.
foreach($this->vars as $key => $value)
{
$$key = $value;
echo "$$Key: " . $$key;
echo "Key: " . $key;
echo "<br/>";
echo "Value: " . $value;
}
</div>
You're looking at a variable variable. e.g.
// original variable named 'foo'
$foo = "bar";
// reference $foo dynamically by evaluating $x
$x = "foo";
echo $$x; // "bar";
echo ${$x}; // "bar" as well but the {} allows you to perform concatenation
// different version of {} to show a more "complex" operation
$y = "fo";
$z = "o";
echo ${$y . $z}; // "bar" also ("fo" . "o" = "foo")
To show an example more closely matching your question:
$foo = "foo";
$bar = "bar";
$baz = "baz";
$ary = array('foo' => 'FOO','bar' => 'BAR','baz' => 'BAZ');
foreach ($ary as $key => $value){
$$key = $value;
}
// end result is:
// $foo = "FOO";
// $bar = "BAR";
// $baz = "BAZ";
Variable variable. The var name is what is contained in $var
.
If $key = 'test'
then $$key
will be evaluate to a var named $test
.
Also, there are very few practical uses. Most often arrays would be better.
It's a variable with the name $key
. For example, If $k='somevar'
, then $$k = $somevar
.