Forum Moderators: coopster

Message Too Old, No Replies

Creating a variable with a variable name

Create a variable that's name changes during a loop

         

chriswragg

3:37 pm on Jun 19, 2005 (gmt 0)

10+ Year Member



I am using a script which contains:

$i=0;
while ($i < $num) {
etc...

but how do I get a variable to take the name of $i, for example $variable$i. I also then want to create a variable which has all the variables created in this loop, for example:

$overall = "$variable0$variable1$variable2" etc....

How is this done?
Any help appreciated

Chris

jatar_k

5:44 pm on Jun 19, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well you will need to use what are called variable variables [php.net]

it does get confusing though so here is an example

$num = 10;
$i=0;
while ($i < $num) {
${'varname' . $i} = 'somevalue';
$i++;
$totalvar .= ${'varname' . $i};
}

this is a pretty redundant example

>> I also then want to create a variable which has all the variables created in this loop

you could really just use an array then

$num = 10;
$i=0;
while ($i < $num) {
$varname[$i] = 'somevalue';
$i++;
}
echo '<pre>';
print_r($varname);
echo '</pre>';

not sure exactly what you are trying to do so neither of those may be the best idea.

mcibor

8:37 pm on Jun 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Where do you get these values? Maybe there's a much better way to accomplish your task. Eg. if you got these values from form (checkboxes, or selects...) it's easy to get.

Moreover see coop wrote about using arrays. Arrays are better than a bunch of variables, because you can do lots of things on them.

Best regards
Michal Cibor

chriswragg

8:51 pm on Jun 20, 2005 (gmt 0)

10+ Year Member



Thanks for your help.

Sorry the thought of searching for 'variable variables' seems rather simple and I feel rather pathetic!

I think your first example jatar_k is the one I need.

Thanks again,

Chris

jatar_k

8:57 pm on Jun 20, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



>> I feel rather pathetic

hehe, no need, took me ages to find those and when I was originally looking I had no idea what to call them.

mcibor

1:17 pm on Jun 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry jatar for calling you "coop". I remembered only that it was a moderator who wrote this previous post and first in my mind was coopster, as he's really fancy with arrays.

Will you ever forgive me? <lol>
Michal

jatar_k

3:57 pm on Jun 21, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I actually thought it was pretty funny, hehe