Can I put associative arrays in form inputs to be processed in PHP?

DLH picture DLH · Jun 24, 2011 · Viewed 24.1k times · Source

I know I can do things like <input name="foo[]">, but is it possible to do things like <input name="foo[bar]"> and have it show up in PHP as $_POST['foo']['bar']?

The reason I ask is because I'm making a huge table of form elements (including <select> with multiple selections), and I want to have my data organized cleanly for the script that I'm POSTing to. I want the input elements in each column to have the same base name, but a different row identifier as an array key. Does that make sense?

EDIT: I tried exactly this already, but apparently Drupal is interfering with what I'm trying to do. I thought I was just getting my syntax wrong. Firebug tells me that my input names are constructed exactly like this, but my data comes back as [foo[bar]] => data rather than [foo] => array([bar] => data).

EDIT 2: It seems my real problem was my assumption that $form_state['values'] in Drupal would have the same array hierarchy as $_POST. I should never have assumed that Drupal would be that reasonable and intuitive. I apologize for wasting your time. You may go about your business.

Answer

Ernest Boabramah picture Ernest Boabramah · Jun 24, 2011

Let say we want to print student scores using the form below:

<form action="" method="POST">
  <input name="student['john']">
  <input name="student['kofi']">
  <input name="student['kwame']">
  <input type="submit" name="submit">
</form>

and PHP code to print their scores:

if(isset($_POST['submit']))
{
    echo $_POST['student']['john'] . '<br />';
    echo $_POST['student']['kofi'] . '<br />';
    echo $_POST['student']['kwame'] . '<br />'; 
}

This will print the values you input into the field.