Reputation: 2531
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?
Upvotes: 1
Views: 217
Reputation: 39356
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.
Upvotes: 5
Reputation: 94157
This should work:
$var = 'offer' . $_GET['id'] . 'name';
$offername = $$var;
See the page on variable variables for more.
Upvotes: 1
Reputation: 57815
You can in addition to the other solutions do:
$offername = ${'offer' . $_GET['id'] . 'name'};
Upvotes: 0
Reputation: 53
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
.
Upvotes: 1