Page 1 of 1

Variable Variables

Posted: Wed Jul 12, 2006 3:40 pm
by Assured99
Can any one explain the Variable Variables to me ??? Im new to PHP and kinda Crusin through a PHP book and i cant seem to get my head around the Variable Variables

Thanks
Snapple

Re: Variable Variables

Posted: Wed Jul 12, 2006 3:49 pm
by Chris Corbyn
Assured99 wrote:Can any one explain the Variable Variables to me ??? Im new to PHP and kinda Crusin through a PHP book and i cant seem to get my head around the Variable Variables

Thanks
Snapple
You know how you give your variables (normal ones) a name? Like $foo would be called "foo"? Well variable variables just use a variable to hold that name.

Code: Select all

$foo = 42;

$variable_name = "foo";

echo $$variable_name; //Parsed as $foo
If you find the need to use these I'd 9 times out of 10 consider re-thinking your design because more often than not it's an array you should be using.

Code: Select all

$var = array();
$var['foo'] = 42;

$variable_name = "foo";

echo $var[$variable_name];
I've only used variable variables in a handful of unusual scenarios :)

Posted: Wed Jul 12, 2006 3:50 pm
by John Cartwright
an explanation can be found in the manual :wink:

Posted: Wed Jul 12, 2006 3:52 pm
by RobertGonzalez
Variable variables are vars that are set to an unknown, or variable, value. This is usually done during a loop of some sort...

Code: Select all

<?php
// Assume $myarray is a filled array of keys and values
foreach ($myarray as $key => $value)
{
    ${$key} = $value;
}
?>
The above code take all the keys in $myarray, and assigns them to vars with the corresponding array key's value as the var value. You might want to have a look at Scottayy's thread on a similar type of question.

PS I agree with the other posters that this is probably not the best method for setting var values and that arrays are much better suited to type of thing.

Posted: Wed Jul 12, 2006 4:21 pm
by Assured99
Thanks and in regards to looking in the manuel, i couldnt get my head around it. Sometimes its just p-lain easier to hear it from someone else and put into perspective

Thanks Everyone