Using a concatenated $ to refer to an existing $

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
Tubusy
Forum Newbie
Posts: 2
Joined: Fri Nov 25, 2011 8:11 pm

Using a concatenated $ to refer to an existing $

Post by Tubusy »

Hi. I still learning and have 'duh' problem. I want a combination of $'s $like$this[$combination] to act like a $ name. I've tried every way I can research.

Example:

Code: Select all

$desc_apple = "A juicy red apple"; $desc_pear = "A sweet tasting pear.";
// ....
$show = '$desc_' . "$fruits[$this]"; // $desc_ is the fixed prefix and not the variable so I put it in single quotes.
echo $show;
Gives

Code: Select all

$desc_apple
and not A juicy red apple.

I even tried things like $show = ${'$desc_' . $fruits[$apple]}; and with no luck. I'm sure I'm being dense, but I don't get it. Help please?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Using a concatenated $ to refer to an existing $

Post by Celauran »

Wouldn't it be easier to just use an array?

Code: Select all

$desc['apple'] = "A juicy red apple";
echo $desc[$fruits[$this]];
Tubusy
Forum Newbie
Posts: 2
Joined: Fri Nov 25, 2011 8:11 pm

Re: Using a concatenated $ to refer to an existing $

Post by Tubusy »

Wow. That works wonderfully. I'd never have thought of that, and so simple.

Thank you very very much Celauran.
Post Reply