16

I need to loop through a post array and sumbit it.

#stuff 1
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
#stuff 2
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />

But I don't know where to start.

Sarfraz
  • 367,681
  • 72
  • 526
  • 573
user1324780
  • 1,619
  • 3
  • 13
  • 11

6 Answers6

40

This is how you would do it:

foreach( $_POST as $stuff ) {
    if( is_array( $stuff ) ) {
        foreach( $stuff as $thing ) {
            echo $thing;
        }
    } else {
        echo $stuff;
    }
}

This looks after both variables and arrays passed in $_POST.

Freesnöw
  • 28,081
  • 30
  • 87
  • 133
gimg1
  • 1,099
  • 10
  • 23
29

Likely, you'll also need the values of each form element, such as the value selected from a dropdown or checkbox.

 foreach( $_POST as $stuff => $val ) {
     if( is_array( $stuff ) ) {
         foreach( $stuff as $thing) {
             echo $thing;
         }
     } else {
         echo $stuff;
         echo $val;
     }
 }
theduck
  • 2,529
  • 13
  • 16
  • 23
glassfish
  • 701
  • 1
  • 9
  • 14
7
for ($i = 0; $i < count($_POST['NAME']); $i++)
{
   echo $_POST['NAME'][$i];
}

Or

foreach ($_POST['NAME'] as $value)
{
    echo $value;
}

Replace NAME with element name eg stuff or more_stuff

Bineesh
  • 486
  • 1
  • 5
  • 18
Sarfraz
  • 367,681
  • 72
  • 526
  • 573
3

I have adapted the accepted answer and converted it into a function that can do nth arrays and to include the keys of the array.

function LoopThrough($array) {
    foreach($array as $key => $val) {
        if (is_array($key))
            LoopThrough($key);
        else 
            echo "{$key} - {$val} <br>";
    }
}

LoopThrough($_POST);

Hope it helps someone.

Eric Aya
  • 69,000
  • 34
  • 174
  • 243
RealSollyM
  • 1,450
  • 1
  • 21
  • 33
2

You can use array_walk_recursive and anonymous function, eg:

$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits,function ($item, $key){
    echo "$key holds $item <br/>\n";
});

follows this answer version:

array_walk_recursive($_POST,function ($item, $key){
    echo "$key holds $item <br/>\n";
});
Ivan Buttinoni
  • 3,942
  • 1
  • 21
  • 37
1

For some reason I lost my index names using the posted answers. Therefore I had to loop them like this:

foreach($_POST as $i => $stuff) {
  var_dump($i);
  var_dump($stuff);
  echo "<br>";
}
Pete
  • 1,181
  • 11
  • 18