skip to Main Content

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


  1. Simply put, you need to loop the items of $_POST['data'] instead of just $_POST

    echo '<pre>';
    var_dump($_POST);
    echo '</pre>';
    
    foreach($_POST['data'] as $key => $item)
    {
        echo $key.':'. $item['row_id'];
    
    }
    
    Login or Signup to reply.
  2. You’re looping over the wrong thing and you’re simultaneously using two different methods to loop over the same thing.

    1. You set $i to 0
    2. Your foreach loop reaches $_POST['data']
    3. You change $i to 1
    4. You access $_POST['data'][1]
    5. You get to the end of the loop

    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 regular for loop.

    When you use foreach you use the variable(s) you define inside it (in this case $key and $value).

    foreach($_POST['data'] as $key => $value) {
        echo $value['row_id']
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search