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.
There are three types of an array in PHP. Numeric Arrays, Associative Arrays, and Multidimensional Arrays. An associative array is in the form of key-value pair, where the key is the index of the array and the value is the element of the array. Here the key can be user-defined.
Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.
Advantages of Associative ArrayWe can save more data, as we can have a string as key to the array element, where we can have associated data to the value to be stored, like in our example, we stored the type of the car as key along with the name of the car as value.
You can create arrays in form fields using square brackets. That means you can name fields like account[first_name] and account[last_name] and in most server-side languages, you will end up with an 'account' array.
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.
Yes you can. you can even do name="foor[bar][]"
and on for even more padding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With