Variable Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Assured99
Forum Commoner
Posts: 81
Joined: Wed Jul 12, 2006 11:48 am
Location: California

Variable Variables

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Variable Variables

Post 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 :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

an explanation can be found in the manual :wink:
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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.
User avatar
Assured99
Forum Commoner
Posts: 81
Joined: Wed Jul 12, 2006 11:48 am
Location: California

Post 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
Post Reply