Forum Moderators: coopster

Message Too Old, No Replies

From the black pit of variable variables

Simple example (that won't work)

         

neophyte

9:44 am on Feb 7, 2008 (gmt 0)

10+ Year Member



Hello All -

I've read and read and read about variable variables but for some reason I just don't understand why the below won't work:

$vName1 = 'Apples';
$vName2 = 'Oranges';
$vName3 = 'Bananas';
$vName4 = 'Grapes';
$vName5 = 'JackFruit';

for($i=1; $i < 6; $i++)
{
$a = 'vName';
$$a = $i;

echo $a${$a} , "<br />"; // Needs to output the CONTENT of the dynamically created var, NOT the NAME of the var.
}

Yes, I'm trying to use this to pre-fill a user-specified number of form fields from within a for loop.

After you create a var name, you CAN get at (echo out) the content can't you?

I know I can do this via an array, but I'm interested in a variable variable possibility as well.

Any insight greatly appreciated.

Neophyte

paulmadillo

11:30 am on Feb 7, 2008 (gmt 0)

10+ Year Member



You've essentially just made a variable of the variable name.

Try this

$vName1 = 'Apples';
$vName2 = 'Oranges';
$vName3 = 'Bananas';
$vName4 = 'Grapes';
$vName5 = 'JackFruit';

for($i=1; $i < 6; $i++)
{
$a = 'vName';
$$a = $i;

$var = "$a${$a}";
echo $$var;
echo "<br />";
}

whoisgregg

6:51 pm on Feb 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can actually concatenate strings inside your variable variable brackets. Taking advantage of that removes some of the headaches.

$vName1 = 'Apples'; 
$vName2 = 'Oranges';
$vName3 = 'Bananas';
$vName4 = 'Grapes';
$vName5 = 'JackFruit';
for($i=1; $i < 6; $i++)
{
echo ${'vName'.$i}.'<br />'; // Apples, Oranges, Bananas, etc.
}

menace_sa

12:33 pm on Feb 8, 2008 (gmt 0)

10+ Year Member



Try putting them into a array

$vName[1] = 'Apples';
$vName[2] = 'Oranges';
$vName[3] = 'Bananas';
$vName[4] = 'Grapes';
$vName[5] = 'JackFruit';

for($i=1; $i < 6; $i++)
{

$a = $vName[$i];
echo $a . "<br />";

}

neophyte

11:59 pm on Feb 8, 2008 (gmt 0)

10+ Year Member



paulmadillo and whoisgregg -

Thank you both so much for replying; I've tried both your techniques and they both work perfectly - I'm leaning toward whoisgregg's way of concatenating the vars just because it's a bit simpler to remember for my simple mind!

Appreciate your guidance very much!

Neophyte