views:

116

answers:

4

Ok this might sound like a dumb question but bear with me. I am trying to make it so that when people go to example.php?id=1, example.php?id=2, example.php?id=3 etc they see different data called from an included file filling in the blanks.

I have a variable called $offername and I want to display $offer1name, $offer2name, $offer3name in that space, depending on what $_GET['id'] says. Ideally, when someone goes to example.php?id=2, $offername will equal $offer2name.

I want to do something like this:

$offername = $offer.$_GET['id'].name

But of course that doesn't work. What should I do?

+1  A: 

This should work:

$var = 'offer' . $_GET['id'] . 'name';
$offername = $$var;

See the page on variable variables for more.

zombat
Thank you very much!
pg
No problem. :)
zombat
I'm learning about them now, it's breaking my head open but I think it will make me smarter.
pg
don't forget to validate $_GET['id'] and check whether $var is set.
Philippe Gerber
So does the following: $offername = ${'offer' . $_GET['id'] . 'name'};
null
Variable variables are my least favourite feature of any language - they are a clear sign that an array or hash should be used instead.
David Dorward
@David D: I second that.
Jason S
A: 

PHP can use variable variables

So you can have $offer_variable_name = 'offer' . $_GET['id'] . 'name';

And then use something like $offername = $$offer_variable_name.

grahamu
+5  A: 

A much cleaner solution is to just use multidimensional arrays.

e.g., instead of

$offername = ${offer.$_GET['id'].name};

use

$offername = $offer[$_GET['id']]['name'];

and define $offer like so:

$offer = array(
  1 => array(
    'name' => 'firstoffer',
  ),
  2 => array(
    'name' => 'secondoffer',
  ),
  3 => array(
    'name' => 'thirdoffer',
  ),
);

I find variable variables difficult to read, and most of the time when I see them used, an array would be much better.

Frank Farmer
A: 

You can in addition to the other solutions do:

$offername = ${'offer' . $_GET['id'] . 'name'};
Tom Haigh