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!

0

3 Answers 3

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]
    }
  ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

So I have a bunch of the following checkboxes: <input type="checkbox" name="teams1member1" />. 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?
w/o JSON, check this.
2
foreach ($_POST as $key => $value) {
    // ...
}

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

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.