How to create a form that handle multiple arrays items

How to create a form that handle multiple arrays items
0

#1

Building a tool to manage text variables, found a php code in a blog that create an array from multiples form item. It works that way:


<?php
//Remove the spaces in PHP opening tag
$variable = $_POST['txtname'];

foreach( $variable as $n ) {
  print "The name is ".$n ."</BR>";
}
?>

<html>
<body>
<form action="" method="post">

<p><label>Enter Name 1</label><input type="text" name="txtname[]" /><br /></p>
<p><label>Enter Name 2</label><input type="text" name="txtname[]" /><br /></p>
<p><label>Enter Name 3</label><input type="text" name="txtname[]" /><br /></p>

<input type="submit" value="Submit and display name by Array"/>
</form>
</body>
</html>

And it gives back a text like that:

The name is [FirstName]
The name is [SecondName]
The name is [ThirdName]

While I need multiple variables for each array, in this example let’s say add age at any people name to have such a result:

This entry is related to [FirstName] which is aged [Age1]
This entry is related to [SecondName] which is aged [Age2]
This entry is related to [ThirdName] which is aged [Age3]

I tried adding an “id” to the paragraph declaration and creating the array from that “id” attribute but it did not work, surely am missing some quite basic php rules but can’t find out which.

Thanks to show your support.


#2

Eh? Just assign a different array to the inputs you use for the ages.


#3

Well, am afraid to almost be a code illiterate. I suppose those it means to create a form like:

<p><label>Enter Name 1</label><input type="text" name="txtname[]" /><br />
<label>Enter Age 1</label><input type="text" name="txtage[]" />
</p>

in this case what should i declare in php statement to correctly manage it?


#4

Exactly the same way as the other one.


#5

I do not think you’re seriously telling what I understood from you’re writing, should I declare it the exact same way how can be managed the print results?

I guess that foreach cycles should be addressed under just one variable set of array and should be declared others in the foreach statement, but how?


#6

If you want to loop over two arrays at the same time, it’s better to use a normal for loop. Otherwise you’d have to jump through hoops to be able to look at the other array.