Pass variable with several input / select

2

I have a form with several input that I create with a for loop, which I pass through POST to another page and change its name as in the example:

<form action="page2.php" method="post">
<?php 
    for($i=1; $i<=10; $i++){ 
?>
<select name=fichier<?php echo $i?> > (...)

The problem is if I do not want to fill in the input or select, how do I get its value? To not repeat the code for the various inpuut I have it on the other page that receives the POST.

for($i=1; $i<=10; $i++){
    if (isset($_POST['fichier'.$i])) 
    {
        $fichier = htmlentities($_POST['fichier'.$i]);
    }

    if(isset($_POST['fichier'.$i])== 0){
        break;
    }
    //echo $fichier;
}
    
asked by anonymous 06.01.2015 / 20:34

2 answers

2

You can name the inputs with brackets at the end, eg:

<?php

if (isset($_POST)) {
    var_dump($_POST);
}

?>

<form method="post">
    <input id="itens[]" name="itens[]" value="text1" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text2" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text3" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text4" type="text" /><br>
    <input type="submit" />
</form>

Output:

array (size=1)
  'itens' => 
    array (size=4)
      0 => string 'text1' (length=5)
      1 => string 'text2' (length=5)
      2 => string 'text3' (length=5)
      3 => string 'text4' (length=5)
    
06.01.2015 / 21:05
0

As you have a form with several input , and you do not want to repeat the values, the solution would be to insert a name with [] at the end so that the values are saved in an array.

Example:

page.html

<form action="page2.php" method="post">
   Input1 <input id="fichier[]" name="fichier[]" type="text" /><br>
   Input2 <input id="fichier[]" name="fichier[]" type="text" /><br>
   Input3 <input id="fichier[]" name="fichier[]" type="text" /><br>
    <input type="submit" value="Enviar" />
</form>

page2.php

<?php 
    if (isset($_POST['fichier'])) {
        var_dump($_POST['fichier']);
    }   
 ?>

Output after POST:

array(3) { [0]=> string(6) "texto1" [1]=> string(6) "texto2" [2]=> string(6) "texto3" }
    
11.01.2015 / 23:04