2 Arrays in foreach from a form

Asked

Viewed 169 times

0

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

Follows 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;
 }
}

?

3 answers

1

The 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 good old for():

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

0

The foreach supports only one collection and not two.

However you can do what you want using array_combine combining names and quantities into a single array, transforming it into an associative array in which names are keys and quantities values:

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

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

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

In which $alimento[i] corresponds to each of the foods and $quantidade[$i] to each of the quantities.

0


You can also do as follows:

foreach($alimento as $key => $value){
   echo "Alimento: {$value}";
   echo "Quantidade: {$quantidade[$key]}";
}
  • Just what I needed friend.. vlw amigoooo

Browser other questions tagged

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