2 Arrays in foreach from a form

0

Good evening everyone! Suppose I have these arrays: alimento[] and quantidade[] How do I put the 2 array in the foreach, I can only put 1 = /

Follow my code:

<form method="POST">
    Feijao<input type="checkbox" name="alimento[]" value="Feijao - "> Quantidade<input type="number" name="quantidade[]"><br>
    Arroz<input type="checkbox" name="alimento[]" value="Arroz"> Quantidade<input type="number" name="quantidade[]"><br>
    <input type="submit" value="Processar">
</form>
<?php
if(isset($_POST['alimento'])){

 $alimento = $_POST['alimento'];
 $quantidade = $_POST['quantidade'];
 foreach($alimento as $k){
    echo $k;
 }
}

?

    
asked by anonymous 26.03.2018 / 02:37

3 answers

0

You can also do this as follows:

foreach($alimento as $key => $value){
   echo "Alimento: {$value}";
   echo "Quantidade: {$quantidade[$key]}";
}
    
26.03.2018 / 03:10
1

foreach () will only work with one array at a time, so it should be one for each. But if both lists have the same number of elements do something using the good old for () :

<?php
   // ...
   for($i=0; $i<count($alimentos); $i++){
        echo $alimentos[$i];
        echo $quantidade[$i];
   }
   // ...
?>
    
26.03.2018 / 03:03
0

foreach supports only one collection, not two.

However, you can do what you want by using array_combine that combines the names and quantities into a single array, transforming it into an associative array where the names are the keys and the quantities the values:

$alimentosQtd = array_combine($alimento, $quantidade);
foreach ($alimentosQtd as $alim => $qtd){
    echo $alim, $qtd;
}

Another solution is to access by position using for instead of foreach :

for ($i = 0; $i < count($alimentos); ++$i){
    echo $alimento[$i], $quantidade[$i];
}

Where $alimento[i] corresponds to each food and $quantidade[$i] to each of the quantities.

    
26.03.2018 / 02:58