-1

Look I have a form like this:

<form method="post">
    <input name="variable[var1][var2]" value="44"/>
</form>

I want to get the value of variable[var1][var2] in PHP using a string like:

$str = "['variable']['var1']['var2']";
echo "{$_POST{$str}}";

Why I need to do that?

I need it because the code that gets the value is totally dynamic and I cannot get or set manually the value using $_POST['variable']['var1']['var2'].

Can you help?

NOTE: I know this is possible to get it using $_POST['variable']['var1']['var2'], please don't ask me about why I'm not using this way. Simply I need to use as above (using $str).

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Sequoya
  • 433
  • 4
  • 16

3 Answers3

2

You can use preg_match_all() to get all the indexes in the string into an array:

$indexes = preg_match_all('/(?<=\[\')(?:[^\']*)(?=\'\])/', $str);
$indexes = $indexes[0]; // Get just the whole matches

Then use a loop to drill into $_POST.

$cur = $_POST;
foreach ($indexes as $index) {
    $cur = $cur[$index];
}

At this point $cur will contain the value you want.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You're WAY overthinking it. Anything you put in [] array notation in a form field's name will just become an array key. The following is LITERALLY all you need:

<input name="foo[bar][baz][qux]" ... />

$val = $_POST['foo']['bar']['baz']['qux'];

You cannot use a string as an "address" into the array, not without insanely ugly hacks like eval, or parsing the string and doing a loop to dig into the array.

Marc B
  • 356,200
  • 43
  • 426
  • 500
-1

It's hard to believe that this is a requirement. If you could expand more on what you're trying to achieve, someone undoubtedly has a better solution. However, I will ignore the eval = evil haters.

To echo:

eval("echo \$_POST$str;");

To assign to a variable:

eval("\$result = \$_POST$str;");

If you're open to another syntax then check How to write getter/setter to access multi-level array by key names?

Community
  • 1
  • 1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87