Adam L.
Adam L.

Reputation: 187

How to loop through dynamic form inputs and insert into an array

I have a form that asks users to input numbers into multiple form fields. They can select how many form fields they would like. I have labelled the form fields as df1, df2, df3 etc. For each extra form field the user adds it will simply plus 1 to the number after df. My problem it trying to capture (using PHP) these fields and put them in an array. To complicate matters the user might not complete a field, e.g. df2 or df15. I am looking for a way to sort through the post form fields that start df1 but eliminate any fields that have been left blank. Then, insert their values (numbers) into an array. Unfortunately, I am getting confused as to how to screen out the posted form fields that are NULL. I have been trying to loop through the fields and increment the number after df but without success.

Any help would be very much appreciated.

Many thanks,

Adam

Upvotes: 1

Views: 3136

Answers (1)

Note that you can also give your form fields indexed names:

<input type="text" name="df[1]" />
<input type="text" name="df[2]" />

They will then be available in an array, for example (depending on your submit method):

foreach ($_GET['df'] as $num => $val) {
    …
}

If the index is left out of the form names, PHP will index them automatically, just as when assigning to an array.

<input name="df[]" />
<input name="df[]" />

You can create multidimensional arrays this way:

<label>Foo</label><input name="df[foo][]" /> <!-- $_REQUEST['df']['foo'][0] -->
<label>Bar</label><input name="df[bar][]" /> <!-- $_REQUEST['df']['bar'][0] -->

<label>Foo</label><input name="df[foo][]" /> <!-- $_REQUEST['df']['foo'][1] -->
<label>Bar</label><input name="df[bar][]" /> <!-- $_REQUEST['df']['bar'][1] -->

Note that each [] will cause the generated index to be incremented. This means it isn't terribly useful for multidimensional arrays, other than for the last index. For example, suppose you wanted each $_REQUEST['df'] to hold an array('foo'=>..., 'bar'=>...). The following wouldn't work:

<label>Foo</label><input name="df[][foo]" /> <!-- $_REQUEST['df'][0]['foo'] -->
<label>Bar</label><input name="df[][bar]" /> <!-- $_REQUEST['df'][1]['bar'] -->

Instead, you'd need:

<label>Foo</label><input name="df[0][foo]" />
<label>Bar</label><input name="df[0][bar]" />

Upvotes: 6

Related Questions