devjs11
devjs11

Reputation: 1948

How to group multiple form inputs in php form for sending

I have a very simple form for products. Each product has a checkbox and quantity field that repeat creating an array of data like this:

<form action="process.php" method="post">
<input type="checkbox" name="product[]" value="product 1" />
<input type="text" name="quantity[]" />

<input type="checkbox" name="product[]" value="product 2" />
<input type="text" name="quantity[]" />

<input type="submit" />
</form>

Then I handle this form the following way in php:

//php script to retrieve data
$product    = isset($_POST['product'])  ? implode(', ', $_POST['product'])  : 'Not selected'; 
$quantity   = isset($_POST['quantity']) ? implode(', ', $_POST['quantity']) : 'Not mentioned'; 

$messageToSend = <<<END

Products:  $product - $quantity

END;

And the output result is for example: Products: product 1, product 2 - 10, 2

But what I am trying to achieve is the following output: Products: product 1 - x 10, product 2 - x 2

Basically what I am trying to figure out is how to split and group data for each product in php script after I retrieved data.

Your help is very much appreciated.

Upvotes: 0

Views: 1750

Answers (2)

Jormundir
Jormundir

Reputation: 395

  1. That doesn't look completely php.
  2. You just have to iterate through both lists together:

    foreach ($quantity as $key => $quant) {
        echo $product[$key].' - x'.$quant;
    }
    

This is the general idea, but as mentioned in the comments, doing this alone will is not the real solution.

Some things to keep in mind:

  1. Checkboxes will not pass a value if they are not checked, so the $product array you get will not be the same size as, nor line up on key values with the $quantity array as you would like. (Try naming your checkboxes differently, I.e. product[1]). - thanks tmuguet
  2. If none of the checkboxes are checked, you will not get an array, so passing it to foreach will generate the error you mentioned.

Upvotes: 3

degt
degt

Reputation: 1

Try this:

<?php 
foreach($_POST['product'] as $key => $product){
   $quantity = isset($_POST['quantity'][$key])? $_POST['quantity'][$key]:'Not selected';
   $message[] = $product.' - x'.$quantity;
}
echo implode(',', $message);
?>

Upvotes: 0

Related Questions