Isset and foreach syntax

Asked

Viewed 55 times

-1

Hello! My question is, can I work with more than two variables in isset and foreach?

have that code:

if(isset($_POST["produto"]) && $_POST["qtd"]){

    echo "Ítens escolhidos:<BR>";
      
    $table  = '<table>';
    $table .= '<thead>';
    $table .= '<tr>';
    $table .= '<td>Produto</td>';
    $table .= '<td>Qtd</td>';
    $table .= '<td>Valor</td>';                                     
    $table .= '</tr>';
    $table .= '</thead>';
    $table .= '<tbody>';
    
    foreach(array_combine($_POST["produto"], $_POST["qtd"]) as $numero =>     $quantidade){

        $table .= '<tr>';                   
        $table .= "<td>{$numero}</td>";
        $table .= "<td>{$quantidade}</td>";
        // $table .= "<td>{$valor}</td>";                               
        $table .= '</tr>';
    
    }
          
    $table .= '</tbody>';
    $table .= '</table>';
                                
    echo $table;
    
}else {

    echo "Você não preencheu o formulário ainda!<br>";
}

I want to insert the value field in isset and foreach, as the syntax?

  • You may call Clayton, see: https://answall.com/a/117504/3635

1 answer

0

I would do so:

if(isset($_POST["produto"],$_POST["valor"]) && $_POST["qtd"] > 0){

echo "Ítens escolhidos:<BR>";
  
$table  = '<table>';
$table .= '<thead>';
$table .= '<tr>';
$table .= '<td>Produto</td>';
$table .= '<td>Qtd</td>';
$table .= '<td>Valor</td>';                                     
$table .= '</tr>';
$table .= '</thead>';
$table .= '<tbody>';

$num_produtos = count($_POST['produto']);

for($x=0;$x<$num_produtos;$x++){
    $numero = $_POST['produto'][$x];
    $quantidade = $_POST['qtd'][$x];
    $valor = $_POST['valor'][$x];

    $table .= '<tr>';                   
    $table .= "<td>{$numero}</td>";
    $table .= "<td>{$quantidade}</td>";
    $table .= "<td>{$valor}</td>";                               
    $table .= '</tr>';

}
      
$table .= '</tbody>';
$table .= '</table>';
                            
echo $table;

}Else {

echo "Você não preencheu o formulário ainda!<br>";

}

Just be careful to declare the sent variables as array:

<form>
   <input name=produto[]>
   <input name=qnt[]>
   <input name=valor[]>
</form>
  • Interesting, only it gave the following error here: Parse error: syntax error, Unexpected '=', expecting ';' in for(x=0;x<$num_products;$x++){

  • was barely missed the $ before the variable

  • I have just learned that isset accepts multiple variables, I will improve the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.