Using a Variable in the Middle of a 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
hyzdufan
Forum Newbie
Posts: 4
Joined: Sat Dec 20, 2008 9:38 pm

Using a Variable in the Middle of a Variable Name

Post by hyzdufan »

I'm having trouble implementing this, and I've tried everything. Take a peek and help if you can. I would be most appreciative.

I have arrays in my code ranging from Site3Needs to Site15Needs.

Code: Select all

while($p < 16)
{
 echo $site.$p.needs;
 $p = $p + 1;
}
How do I correctly reference $p in the middle of that site#needs variable?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Using a Variable in the Middle of a Variable Name

Post by Chris Corbyn »

Code: Select all

$site13needs = 'foo';
 
$i = 13;
 
echo ${'site' . $i . 'needs'};
By the way, I found your code is little illogical. I'd suggest a for loop instead of your while.
hyzdufan
Forum Newbie
Posts: 4
Joined: Sat Dec 20, 2008 9:38 pm

Re: Using a Variable in the Middle of a Variable Name

Post by hyzdufan »

Thank you so much!
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Using a Variable in the Middle of a Variable Name

Post by josh »

alternatively ( but inferior in this simple case )

Code: Select all

 
$foobar=123;
$a = 'foo';
$b='bar';
$var = $a . $b;
echo $$var; // 'variable variables'
 
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Using a Variable in the Middle of a Variable Name

Post by Chris Corbyn »

Whenever people ask this question I always wonder if what they really need is an array. Variable-variables are useful in rare edge-cases but if you really are dealing with variables named $something16other and so on, then you probably should be using an array.
Post Reply