PHP how to loop through a post array
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.
Solution 1:
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
.
Solution 2:
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;
}
}