Search only form fields with a value other than 0 and put in PHP variable

2

I have a budget form with 70 products in which the user chooses the quantity of products he wants from each one.

All are named with id p1, p2 ... p70 and are type inputs.

<form method="post">
<input type="number" value="0" name="p1" id="p1">
<input type="number" value="0" name="p2" id="p2">
...
<input type="number" value="0" name="p70" id="p70">
</form>

I need a PHP function that only inserts items that are different from 0 (which is the default value) into a variable to mount a table that will be exported to excel.

What I have is the following:

// Monta o cabeçalho da tabela    
$data = '<table><tbody><tr><td>CABEÇALHO</td></tr>';

// Traz cada linha que o valor é diferente de 0
if($_POST['form']['p1'] != '0'){
    $data .= '<tr><td>'.$_POST["form"]["p1"].'</td></tr>';
}
if($_POST['form']['p2'] != '0'){
    $data .= '<tr><td>'.$_POST["form"]["p2"].'</td></tr>';
}

// Coloca o rodapé e fecha a tabela
$data .= '<tr><td>RODAPÉ</td></tr></tbody></table>';

The problem that I have made is that I would have to have 70 ifs, I believe there should be a simpler form, but I do not know which one.

    
asked by anonymous 28.08.2017 / 20:50

2 answers

2

Loops from 1 to 70 by creating rows where the value of $_POST is different from 0:

    <?php
$data = '<table><tbody><tr><td>CABEÇALHO</td></tr>';

for($x=1;$x<=70;$x++){
  if($_POST['form']['p'.$x] != '0'){
   $data .= '<tr><td>'.$_POST['form']['p'.$x].'</td></tr>';
  }
}

$data .= '<tr><td>RODAPÉ</td></tr></tbody</table>';
    ?>
    
28.08.2017 / 20:58
3
<?php 
cabeçalho...

foreach($_POST['form'] as $value){
   $table .= ($value) ? '<tr><td>'.$value.'</td></tr>'; : '';
}

footer...

If there are changes in the quantity of items, the code still needs to work.

    
28.08.2017 / 21:06