HTML Form - Passing Array

I am trying to figure out a way to pass an array to php to get processed.

Lets say I have a checkbox, the value is add[]

I want to pass 2 other form elements with this, lets just say a text aera. We will give the text aeras a value of text1[] and text2[]

I added the array [] to the end cause I expect to have multiple. The function of the checkbox is just a true or false, if checked, do someting.

So here is what we got so far

checkbox:add[]
text: text1[]
text: text2[]

I want to have multiple instances of this in my html form.

[b]checkbox:add[]
text: text1[]
text: text2[]

checkbox:add[]
text: text1[]
text: text2[]

checkbox:add[]
text: text1[]
text: text2[][/b]

After submiting, I want to look through the results, and display them

if checkbox is true
print value of text1[]
print value of text2[]

I can easily loop 1 html element, for example :

$checkbox = $_POST[add]; if($checkbox){ foreach($checkbox as $check){ print $check; } }

If I had three instances of the checkbox, and all three were checked it would print the value of the checkbox (1) 3 times.

How would I do this tieing multiple values to the checkbox. I tried nesting for each loops, but that jsut gave me all the results multiple times. Is there a way to pass a multidimentional array from an html form?

Maybe somehow I could name the form elements the same name, and then call the key?

[b]element[add]
element[text1]
element[text2]

element[0][0]
element[0][1]
element[0][2]

element[1][0]
element[1][1]
element[1][2][/b]

And if so, how in the world would I loop that?

Hummm…

The initial setup you proposed with add[], text1[] and text2[] (you should be using better names) should be fine. The only problem is that the checkboxes are not sent to PHP unless they are checked, which means there is a mismatch between the index numbers in your different lists. There are 2 ways to solve this:

  • Force the index numbers in the form field names (ex: add[0], add[1], …) and make sure the indexes are the same for all lists.
  • Instead of giving a value of 1 to the checkbox, give it the index number.

There are more solutions, but those are the closest to what you have.

Sponsor our Newsletter | Privacy Policy | Terms of Service