I have a loop below that is showing a quantity box and includes a hidden field containing the product name.
I want these to be tied together so if out of 100 inputs the
You obviously need to iterate over both arrays in tandem so that you can see if a product's quantity is nonzero in order to decide if it should be displayed.
In general foreach
is an awkward tool for this job, and the way to go is with a for
loop and indexing into both arrays using the same counter. However, in this specific case you can easily transform your two arrays into one where the keys are product names and the quantities are the values using array_combine:
$quantities = array_combine($_POST['product'], $_POST['quantity']);
You can then easily iterate with foreach
:
foreach ($quantities as $product => $quantity) {
if ($quantity > 0) {
echo "$quantity x $product
";
}
}