Retrieving array elements from a web form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Retrieving array elements from a web form

Post by sparky753 »

I have a web form that has hidden fields that are dynamically generated. I want to be able to pass these to another page on submission, and I can't seem to figure out how to do it.

$namearray is an array that has the product names


Code: Select all

<?php 
    for ($i=0;$i<sizeof($namearray);$i++){ 
  ?>

Code: Select all

<input type='text' name='productname<?= $i  ?>' value='<?= $namearray[$i]?>'

Code: Select all

<?php 
  } 
 ?>


Normally on the page that handles the form submission, we handle the submitted values thus:

Code: Select all

$name = $_POST['name'];


How do I do the same thing for a field that is based on an array? for instance, in the page that has the form, if 5 products were selected, the dynamically generated text fields would be:

<input type='text' name='productname0' value='paper' >
<input type='text' name='productname1' value='pencil' >
<input type='text' name='productname2' value='pen' >
<input type='text' name='productname3' value='notebook' >
<input type='text' name='productname4' value='eraser' >

How would I submit these fields' values to another page?

Thanks...
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Unless they become a part of a form for each page to be sent to, I'd suggest you storing them in a session during the for loop.
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

You can dynamically generate your inputs as follows

Code: Select all

<input type="text" name="products[0]" value="taco">
<input type="text" name="products[1]" value="burrito">
<input type="text" name="products[2]" value="flauta">
then on your submission page

Code: Select all

$products = $_POST['products'] ;

foreach( $products as $product )
{
  // do stuff
}
sparky753
Forum Commoner
Posts: 51
Joined: Fri Nov 03, 2006 10:39 am

Post by sparky753 »

Awesome!! Thanks Begby!! That worked....
Post Reply