user1324780
user1324780

Reputation: 1689

Loop through a POST array

I need to loop through a post array and submit 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.

Upvotes: 16

Views: 66327

Answers (6)

glassfish
glassfish

Reputation: 721

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;
     }
 }

Upvotes: 30

RealSollyM
RealSollyM

Reputation: 1530

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.

Upvotes: 3

Pete
Pete

Reputation: 1261

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>";
}

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382616

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

Upvotes: 7

Ivan Buttinoni
Ivan Buttinoni

Reputation: 4145

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";
});

Upvotes: 2

gimg1
gimg1

Reputation: 1167

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.

Upvotes: 41

Related Questions