Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to loop through a post array

Tags:

post

php

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.

like image 540
user1324780 Avatar asked Apr 21 '12 20:04

user1324780


People also ask

Which loop would you prefer to go through an array in PHP briefly describe?

If you have an array variable, and you want to go through each element of that array, the foreach loop is the best choice.

What is the $_ POST array?

$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request. $HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated.


3 Answers

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.

like image 128
gimg1 Avatar answered Oct 14 '22 01:10

gimg1


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;
     }
 }
like image 22
glassfish Avatar answered Oct 14 '22 00:10

glassfish


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

like image 31
Sarfraz Avatar answered Oct 14 '22 01:10

Sarfraz