Andelas Andelas - 1 month ago 4
PHP Question

Foreach value from POST from form

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.

What would be the best way to loop through those items to get the values?

Here's what I have, which obviously isn't working.

extract($_POST);

$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop

while(${'item_name_' .$x} != '') {

echo ${'item_name' .$x};

$x++;

}


I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.

Thanks.

Answer

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}
Comments