-1

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?

sjagr
  • 15,983
  • 5
  • 40
  • 67
Philip
  • 1,068
  • 3
  • 12
  • 21

4 Answers4

2

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];
Community
  • 1
  • 1
Mathew Tinsley
  • 6,805
  • 2
  • 27
  • 37
1

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];
Community
  • 1
  • 1
Mooseman
  • 18,763
  • 14
  • 70
  • 93
0

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"

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    This method does not work. PHP is trying to reference a variable with the name `$method[$var]`. You get an illegal string offset notice because `$method` is _GET. – Mathew Tinsley Jan 05 '15 at 16:44
  • thats what I get, any ideas? – Philip Jan 05 '15 at 16:47
  • @Philip see my answer, it isn't a one liner but I tested it and it works. – Mathew Tinsley Jan 05 '15 at 16:48
  • 1
    Figures... yay for php parse consistency. Had no idea that arrays couldn't be var-var'd... – Marc B Jan 05 '15 at 16:49
  • I like your answer the best still because you have corrected the ambiguity mistake with proper referencing to the PHP docs as the supported way to prevent ambiguity. – sjagr Jan 05 '15 at 16:56
0

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.

War10ck
  • 12,387
  • 7
  • 41
  • 54