0

I might just be tired or something, but I can't figure out how I can, based on an <input>'s name attribute access the correct $_POST variable.

With simple inputs it's easy;

<input name="email">

$inputName = 'email';
$inputValue = $_POST[$inputName];

But how does it work with arrays?

<input name="foo[bar][0]">

$inputName = 'foo[bar][0]';
$inputValue = $_POST[$inputName]; # Obviously fails...

So how can I convert this to $_POST[foo][bar][0], is there some built in PHP function for this?

I'm not sure how this is a duplicate of that other question seeing as he wants to access an array using dot.separation and I want to use the standard form name way?

A little more background; This is for a Form handling PHP class I'm building, where the user can add fields like this:

$form->addField(['name' => 'my[field][name]']);

And later when I want to fetch the value of the submitted field all I have to go by is the name specified by the user.

If I was manually doing this I would obviously just write $_POST[foo][bar][0] but now I can never know the name of the field and thus I have to parse it somehow.

Ok so this has expanded a bit into me having to know, based on an input name, what that input's value is, or if that input is selected (for select, radio elements) or if that input is part of an array of values (multiple select, checkboxes). I'd also like it to support any input name, such as foo[bar][][][baz][12][].

If anyone has done something similar I'd love to hear about it, but it's leaning towards me writing custom code for this myself.

powerbuoy
  • 11,015
  • 5
  • 38
  • 68
  • 1
    print_r($_POST) and you will see the post array – CatalinB Sep 23 '16 at 13:01
  • Why do you have to convert? If you see the `$_POST` array, you'll get `$_POST[foo][bar][0]` there itself – Object Manipulator Sep 23 '16 at 13:02
  • print_r($_POST) you will get all post data from this array – Bhavin Sep 23 '16 at 13:03
  • Accessing $_POST directly? Why not use any kind of framework to help sanitize and validate incoming data? – Kwebble Sep 23 '16 at 13:05
  • `$_POST['foo']['bar'][0]` – devpro Sep 23 '16 at 13:07
  • 1
    You'd be better off using something like http://stackoverflow.com/questions/27929875/how-to-write-getter-setter-to-access-multi-level-array-by-key-names. But there was an exact dupe. – AbraCadaver Sep 23 '16 at 13:09
  • Alright so there's nothing built in for this type of thing? I thought maybe I was onto something when I found `filter_input(INPUT_POST, 'my[field][name]', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);` but that doesn't seem to do what I want :/ – powerbuoy Sep 23 '16 at 13:12

1 Answers1

-2

you cand access like this $_POST['foo']['bar'][0];

CatalinB
  • 471
  • 4
  • 10