Page 1 of 1
Using a Variable in the Middle of a Variable Name
Posted: Sat Dec 20, 2008 9:41 pm
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?
Re: Using a Variable in the Middle of a Variable Name
Posted: Sat Dec 20, 2008 9:58 pm
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.
Re: Using a Variable in the Middle of a Variable Name
Posted: Sat Dec 20, 2008 10:23 pm
by hyzdufan
Thank you so much!
Re: Using a Variable in the Middle of a Variable Name
Posted: Sun Dec 21, 2008 12:54 am
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'
Re: Using a Variable in the Middle of a Variable Name
Posted: Sun Dec 21, 2008 4:56 am
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.