Page 1 of 1

Can I set variables using variables?

Posted: Thu Jan 11, 2007 1:48 pm
by bwv2
I have an array, let's say it's the following:

Code: Select all

$array=("see","the","squirrel","be","the","monkey");
Only in real life, the array has a whole lotta entries (maybe 100, maybe 500, who knows?). I would like to make a concatonated variable using each of these array entries. These concatonated variables will be used later in the same page. For instance, I think it should work the following way (but it doesn't):

Code: Select all

foreach($array as $words){
  $words._test = $words." works";
}
Let's assume this worked. If it did, then the following call would produce the result that follows it:

Code: Select all

print"List of variables:<br> $see_test <br> $the_test <br> $squirrel_test <br> $be_test <br> $the_test <br> $monkey_test";

//-----produces the following:
List of variables:
see works
the works
squirrel works
be works
the works
monkey works
Now, bear in mind this DOES NOT work. Does anyone know how to make it work? I want to make variables called names that come from variables concatonated with strings. These are a few of my favorite things.

Posted: Thu Jan 11, 2007 1:50 pm
by Luke

Posted: Thu Jan 11, 2007 1:52 pm
by Kieran Huggins

Code: Select all

foreach($array as $word){
  $names[] = $word." works";
}
:?:

Re: Can I set variables using variables?

Posted: Thu Jan 11, 2007 1:58 pm
by pickle
bwv2 wrote:

Code: Select all

foreach($array as $words){
  $words._test = $words." works";
}
That's very close. This would be what you want:

Code: Select all

foreach($array as $word)
{
  ${$word.'_test'} = $word.' works';
}

Posted: Thu Jan 11, 2007 2:10 pm
by volka
I'd rather use the array as Kieran Huggins suggested than to pollute the scope with all that variables.

Posted: Thu Jan 11, 2007 2:33 pm
by Luke
yea there has never been a time when I have used variable variables over an (associative) array. I can't even think of when they would be necessary.