Error "Invalid argument supplied for foreach ()" and "Undefined index" in PHP form

-4

I need to create 20 inputs which, when filled in, should show what was typed in them below, using arrays and foreach, here is the code below:

function repeteInput(){
    for($i = 1; $i <= 20; $i++){
        echo '<form action="repeteInput.php" method="post">';
        echo 'Digite um número aqui ('.$i.')<input type="text" name "produto[]"><br>';
    }
    echo '<input type="submit" value="Enviar"></form>';
    $produtos = $_POST['produto'];
    foreach ($produtos as $produto){
        echo $produto."<br>";
    }
}

echo repeteInput();

I've already checked the code, and it looks exactly the same as what I copied in my notebook, which had worked on another PC. Even so, it shows this error after the page:

Notice: Undefined index: produto in C:\xampp\htdocs.04.2017\repeteInput.php on line 8

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs.04.2017\repeteInput.php on line 9
    
asked by anonymous 28.04.2017 / 16:01

1 answer

1

In this case $ product = $ _POST ['product']; not getting an array, try this

<form action="" method="POST">
    <input type="text" name="test1">
    <input type="text" name="test2">
    <input type="text" name="test3">
    <input type="text" name="test4">
    <input type="text" name="test5">

    <button type="submit">Enviar</button>
</form>

<?php
    foreach ($_POST as $produto) {
        echo $produto . "<br>";
    }
?>

Considering your need, I suggest something like this: Obs. Understand that this is just an example to aid you in thinking, in production there are better ways of doing what you need.

<form action="" method="POST">
    <?php
        for($i = 1; $i <= 20; $i++)
        {
            echo "<label>Produto $i: </label>";
            echo "<input type='text' name='$i' value=''><br>";
        }

    ?>
    <button type="submit">Enviar</button>
    <hr>
</form>

<?php
    foreach ($_POST as $key => $produto) {
        echo "Nº: " . $key. " - Produto: " .$produto . "<br>";
    }
?>

Code that produces the same effect

<form action="" method="POST">
    <?php
        for($i = 1; $i <= 20; $i++)
        {
            echo "<label>Produto $i: ";
            echo "<input type='text' name='".$produto[] = $i."' value=''><br>";
        }

    ?>
    <button type="submit">Enviar</button>
    <hr>
</form>

<?php
    foreach ($_POST as $key => $produto) {
        echo "Nº: " . $key. " - Produto: " .$produto. "<br>";
    }
?>
    
28.04.2017 / 16:13