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
  • 377,238
  • 77
  • 533
  • 578
user1324780
  • 1,649
  • 3
  • 14
  • 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
  • 30,619
  • 30
  • 89
  • 138
gimg1
  • 1,121
  • 10
  • 24
30

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,589
  • 13
  • 17
  • 23
glassfish
  • 721
  • 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
  • 494
  • 1
  • 5
  • 18
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
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,473
  • 35
  • 181
  • 253
RealSollyM
  • 1,530
  • 1
  • 22
  • 35
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
  • 4,110
  • 1
  • 24
  • 44
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,191
  • 12
  • 19