By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,409 Members | 1,604 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,409 IT Pros & Developers. It's quick & easy.

Dereferencing Variables in PHP

P: n/a
I have a set of variables called $topten_1, $topten_2, $topten_3, etc.

I'd like to use a for($i = 1 ; $i<=10 ; $i++) loop to reference them,
but can't quite figure out how to. These don't work:

$topten_$1
${topten_$1}
$"topten_$1"

Is there someway to do this in PHP, or is the only answer to use an
associative array?

Shannon

Jul 17 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Shannon A. wrote:
I have a set of variables called $topten_1, $topten_2, $topten_3, etc.

I'd like to use a for($i = 1 ; $i<=10 ; $i++) loop to reference them,
but can't quite figure out how to. These don't work:

$topten_$1
${topten_$1}
$"topten_$1"

Is there someway to do this in PHP, or is the only answer to use an
associative array?

Shannon


Shannon,

Something like this should work...

$var = 'topten_' . $i;
echo $$var;

But I'd use an array. Much cleaner code and easier to do. Since you're
using integer indicies anyway, it doesn't have to be associative.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Jul 17 '05 #2

P: n/a
"Shannon A." <ap***@erzo.org> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
I have a set of variables called $topten_1, $topten_2, $topten_3, etc.

I'd like to use a for($i = 1 ; $i<=10 ; $i++) loop to reference them,
but can't quite figure out how to. These don't work:

$topten_$1
${topten_$1}
$"topten_$1"

Is there someway to do this in PHP, or is the only answer to use an
associative array?

Shannon


Close... try:

${"topten_$i"}

Norm
---
FREE Avatar hosting at www.easyavatar.com
Jul 17 '05 #3

P: n/a
Shannon A. wrote:
I have a set of variables called $topten_1, $topten_2, $topten_3, etc.
I'd like to use a for($i = 1 ; $i<=10 ; $i++) loop to reference them,
but can't quite figure out how to. These don't work:

$topten_$1
${topten_$1}
$"topten_$1"
Don't use this approach, it's just a complete pain. Use an array, it's
far easier and there's dozens of PHP functions there to help you do
this.
Is there someway to do this in PHP, or is the only answer to use an
associative array?


You don't even have to use an associative array, numeric indices will
do the trick, e.g.

$topten[1]
$topten[2]
etc...

--
Oli

Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.