Making a Dynamic Variable name

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
Nick99
Forum Newbie
Posts: 2
Joined: Wed May 21, 2008 7:08 am

Making a Dynamic Variable name

Post by Nick99 »

Hey would I be able to make a variable name Dynamic? Maybe I can show you through an example

Code: Select all

$variable = 12;
 
if ($variable == 12){
//make variable name to "VARIABLE2"
}
 
print("$VARIABALE2");
Any help would be GREATLT appreciated
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Making a Dynamic Variable name

Post by VladSun »

You mean like:

Code: Select all

 
$var_name = 'variable1';
 
$$var_name = 2;
 
echo $variable1;
 
There are 10 types of people in this world, those who understand binary and those who don't
Nick99
Forum Newbie
Posts: 2
Joined: Wed May 21, 2008 7:08 am

Re: Making a Dynamic Variable name

Post by Nick99 »

Could you please explain that example? Why do you have 2 $'s? Sorry if I'm annoying but I'm sort of new to PHP.



oh I think I understand, you have a variable in a variable, then set it?
LSJason
Forum Commoner
Posts: 45
Joined: Mon May 12, 2008 4:43 pm

Re: Making a Dynamic Variable name

Post by LSJason »

Nick99 wrote:Could you please explain that example? Why do you have 2 $'s? Sorry if I'm annoying but I'm sort of new to PHP.



oh I think I understand, you have a variable in a variable, then set it?

Code: Select all

 
$var_name = 'variable1';
$$var_name = 2;
echo $variable1;
 
That code is processed the same way that this would be:

Code: Select all

 
$var_name = 'variable1';
${$var_name} = 2;
echo $variable1;
 
Now...some third grade math...objects in parenthesis/brackets get evaluated first, so:

Code: Select all

 
$var_name = 'variable1';
$variable1 = 2;
echo $variable1;
 
Post Reply