0

My question is, How to add data into array by HTML input and not only one value but add as much as I want

<body>
    <form action="oop.php" method="post">
        <input type="number" name="no[]">
        <input type="number" name='no[]">
        <input type="number" name="no[]">
        <input type="submit" name="sub">
    </form> 
</body>
</html>
<?php
if (isset($_POST['sub'])) {
    $no= $_POST['no'];
    $ex = explode(",", $no);
    $item = array ();
    foreach ($ex as $item) {
        echo $item; // Do something with item
        print_r($item);
    }
}
?>

THANKS IN ADVANCE

Amit Sharma
  • 1,775
  • 3
  • 11
  • 20
AzanKorejo
  • 38
  • 7

3 Answers3

1

you are doing it correctly. you just need to print the item valus outside the foreach loop. Inside the loop it will always print the last value

<?php
if (isset($_POST['sub'])) {
  $no= $_POST['no'];
 // $ex = explode(",", $no);
  $items = array ();
  foreach ($no as $item) {
      echo $item; // Do something with item
       $items[] = $item;
   }
   print_r($items);

}
?>
Amit Sharma
  • 1,775
  • 3
  • 11
  • 20
0

This should do it :

<?php
if (isset($_POST['sub'])) {
    $no= $_POST['no'];
    $nos = explode(",", $no);
    $items = array (); // careful here you are using $item twice !
    foreach ($nos as $no) {
        $items[] = $no;
    }
    var_dump($items);
}
?>
Loïc
  • 11,804
  • 1
  • 31
  • 49
0

When you use this pattern no[] then you are sending an array so there is no need to use explode.

also the line $item = array (); doing nothing becouse you are filling $item in the foreach.

So, change your code as follow:

<body>
<form action="array_check.php" method="post">
    <input type="number" name="no[]">
    <input type="number" name="no[]">
    <input type="number" name="no[]">
    <input type="submit" name="sub">
</form>
</body>
</html>
<?php
if (isset($_POST['sub'])) {
    $no = $_POST['no'];
    foreach ($no as $item) {
        echo $item ; // Do something with item
        print_r($item);
    }
}
Arash Rabiee
  • 1,019
  • 2
  • 16
  • 31