Reputation: 19
The following example works fine:
$name = 'MrSmith';
$var = 'name';
echo ${$var};
But when submitted I need to use $_REQUEST
and I can not figure out how to write it. This did not work:
$_REQUEST[${$var}]
What is the correct syntax for this?
Upvotes: 0
Views: 254
Reputation: 5649
$$var
is a variable variable. If $var
is equal to 'name' as described in your question it will look for the variable $name
. $name
is undefined. Consider the following:
$var = 'name';
$_REQUEST['name'] = 'test';
$_REQUEST[$$var]; // is the same as...
$_REQUEST[$name]; // which is the same as...
$_REQUEST[NULL]; // since $name is not set.
echo $_REQUEST[$var]; // prints 'test' because $var evaluates to 'name'.
Upvotes: 0
Reputation: 16666
I think you just want:
$_REQUEST[$var];
This will give you the value of $_REQUEST['name']
if $var
= 'name'
Also for your original example, this also works:
echo $$var;
I suggest reading the section on variable variables.
Upvotes: 4