Look I have a form like this:
I want t
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.
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.
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?