This question already has an answer here:
HTML
//index.php
<form name="test" action="form.php" method="post">
name="model<?php echo $key ?>"
name="qty<?php echo $key ?>"
name="msrp<?php echo $key ?>"
</form>
PHP
foreach($_POST as $key => $value) {
//I want to print only items with qty>0
if (("qty" == substr($key, 0, 3) && $value > 0))
{
echo $key, ' => ', $value, '<br />';
}}
OUTPUT of post array print_r($_POST) looks like this (inputs has been loaded)
Array([model1] => FSE 30 [msrp1] => 129.95 [qty1]=1
[model2] => FS 38 [msrp] => 129.95 [qty2]=3
[model3] => FS 60 [msrp] => 159.95 [qty3]=4
[model4] => FS 70 [msrp] => 169.95 [qty4]=0)
MY OUTPUT:
qty1 => 1
qty2 => 3
qty3 => 4
I WANT OUTPUT:
model1 =>FS 30 qty1 => 1 msrp=>129.95
model2 => FS 38 qty2 => 3 msrp=> 129.95
model3 => FS 60 qty3 => 4 msrp=> 159.95
In for loop I want to print only items with value of array qty>0 and it only showed qty in output. How I do print items with qty>0 together with msrp and model ? Thanks
</div>
You'll need to take the index value from the key
then concatanate it with the other indices to get your values. Using an array as the names in HTML would be easier.
Current approach:
foreach($_POST as $key => $value) {
if (("qty" == substr($key, 0, 3) && $value > 0)) {
$id = substr($key, 3);
echo 'qty' . $id . ' => ' . $value .
'model' . $id . ' => '. $_POST['model' . $id] .
'msrp' . $id . ' => ' . $_POST['msrp' . $id] ;
}
}
The alternative, and I think cleaner, approach would be:
<form name="test" action="form.php" method="post">
name="model[]"
name="qty[]"
name="msrp[]"
name"id[]" type="hidden" value="<?php echo $key;?>"
</form>
Then iterate over it:
foreach($_POST['qty'] as $key => $qty) {
echo 'qty = ' . $qty . "<br> model = " . $_POST['model'][$key];
//etc....
}