I have a very simple form on my website.
I run this PHP to loop the form contents:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
$i = 0;
foreach($_POST as $key => $value)
{
$i++;
echo $value[$i]['row_id'];
}
I get the below:
array(1) {
["data"]=> array(2) {
[1]=> array(2) {
["row_id"]=> string(5) "33714"
["sport"]=> string(8) "swimming"
}
[2]=> array(2) {
["row_id"]=> string(5) "33715"
["sport"]=> string(8) "football"
}
}
}
33714
My PHP only echoes the first row id 33714
instead of both rows.
I feel I’m missing something obvious here.
2
Answers
Simply put, you need to loop the items of
$_POST['data']
instead of just$_POST
You’re looping over the wrong thing and you’re simultaneously using two different methods to loop over the same thing.
$i
to0
foreach
loop reaches$_POST['data']
$i
to1
$_POST['data'][1]
You need to loop over what you actually want to loop over.
data
is a fixed thing, so hard code that. Then loop over the array it contains.Only use a
$i
variable if you are using a regularfor
loop.When you use
foreach
you use the variable(s) you define inside it (in this case$key
and$value
).