Can I set variables using 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
bwv2
Forum Commoner
Posts: 83
Joined: Fri Jun 10, 2005 11:50 am
Location: AZ

Can I set variables using variables?

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Code: Select all

foreach($array as $word){
  $names[] = $word." works";
}
:?:
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Can I set variables using variables?

Post 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';
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I'd rather use the array as Kieran Huggins suggested than to pollute the scope with all that variables.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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