tags:

views:

32

answers:

1

Hi,

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

+4  A: 

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) {
    …
}
Scytale
Thank you for your help. How would I go about removing those values that are NULL from the array? Many thanks, Adam
Adam Lund
There will be no null values in the array, because either the value is a (probably empty) string or it is not present in the array at all. You may want to check whether the string is empty inside your foreach loop, for example by testing „if (empty($val)) …“ or „if (trim($val)) …“. The latter ignores text fields which contain nothing but whitespace.
Scytale
Again, thank you for your help. Using the term NULL was incorrect on my part and I actually meant empty like you have pointed out. My problem is how to eliminate the array position that has an empty value. For example, turing df[1,7,3,,4] into df[1,7,3,4]. This is what I am really struggling at, as I need a "clean" array for calculations later on. Many thanks, Adam
Adam Lund
In that case, add something like “if (empty($val)) { unset($_GET['df'][$num]); }” inside your loop. Or, construct a new, empty array and fill it with the values of your choice.
Scytale
Many thanks for all your help. That worked!
Adam Lund
Glad I could help.
Scytale