0

So I'm trying to get dynamic data from the $_POST array. The $_POST array looks like this after the form submit:

Array
(
    [teams1member3] => on
    [teams1member4] => on
    [teams1member7] => on
    [teams1member8] => on
    [teams2member1] => on
)

Now I'm not entirely sure how I can access these, the teams can be any number and the same goes for a member. Is there a way to "read" the [teams1member3]?

I tried looping through the $_POST variable with a foreach loop (foreach($_POST as $post)), but this only gets the value (on). If I'm able to get the teams1member3, teams1member4, etc. I should be able to continue.

Anyone that can help me out? Much appreciated!

wesley221
  • 67
  • 2
  • 10

3 Answers3

3

You should use the $key => $value syntax:

foreach($_POST as $key => $post){
   // $key is what you need
}

But you should rather serialise your $_POST data better, consider using the following JSON notation:

{
  "teams" : [
    {
      "id": 1,
      "members": [3, 4, 7, 8]
    },
    {
      "id": 2,
      "members": [1]
    }
  ]
}
moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • So I have a bunch of the following checkboxes: ``. Depending on whether they are checked or not I want them to be visible in an array. Is this possible to do through HTML or am I going to have to do something with JS/PHP to make this possible? – wesley221 Apr 08 '17 at 14:41
  • w/o JSON, [check this](https://stackoverflow.com/questions/20184670/html-php-form-input-as-array). – moonwave99 Apr 08 '17 at 14:44
2
foreach ($_POST as $key => $value) {
    // ...
}

$key will contain array keys (what you need), $value - string "on".

ghostprgmr
  • 488
  • 2
  • 11
1

if you just use foreach($_POST as $value) , you will only get the values - in your case on and off

However, if you want the actual field name, you have to specify key and value in your foreach:

foreach($_POST a $key => $value) {
  //$key contains teammember
  //$value contains on
}
Youn Elan
  • 2,379
  • 3
  • 23
  • 32