I have two variables:
$method = "_GET";
$var = "id";
I now need this:
$parameter = $_GET['id'];
I tried something like this:
$parameter = ${$method.'[\''.$var.'\']'};
But it doesn't work. Any ideas?
I have two variables:
$method = "_GET";
$var = "id";
I now need this:
$parameter = $_GET['id'];
I tried something like this:
$parameter = ${$method.'[\''.$var.'\']'};
But it doesn't work. Any ideas?
Try:
$data = $$method;
$parameter = $data[ $var ];
The following:
$method = '_GET';
$var = 'id';
$data = $$method;
print_r($data);
echo $data[ $var ];
Will output:
Array
(
[id] => test
)
test
Assuming the query string is ?id=test
@Leggendario pointed out an interested caveat: This won't work outside of the global scope, even though $_GET is a super global. You have to add global $$method
before you can reference $$method
in a function.
Also, it turns out there is a one-liner that will do this:
${$method}[$var];
Since you're not concentrating any strings to form the variable name, just put it in {}
:
$parameter = ${$method}[$var];
Another possible solution, since the only two methods are _GET
and _POST
, is to use a ternary operator instead:
$parameter = $method == "_GET" ? $_GET[$var] : $_POST[$var];
That's basically a variable-variable:
$method = '_GET';
$var = 'id';
$foo = $$method[$var];
Turns out to not work at all... Yay php consistency, and I've learned my new thing for today.
This works:
php > $_GET['id'] = 'foo';
php > $method = '_GET';
php > $offset = 'id';
php > echo ${$method}[$offset];
foo
and turns out to have been documented: http://php.net/manual/en/language.variables.variable.php search for "ambiguity"
You could try the following:
filter_input(constant("INPUT" . $method), $var);
The constant()
function let's you reference the INPUT_GET
constant value for the filter_input()
function by string name.
Using this method, you are retrieving the value and have the option to filter/sanitize it using the filter values on this page for extra security all in one setup.