doukuang1897
doukuang1897
2019-07-03 20:51

有没有办法在循环中获取$ _POST变量?

已采纳

Is there a way to make a loop that would give me this, depending on the number of users I want to grab?

$user1 = htmlentities($_POST['user1']);
$user2 = htmlentities($_POST['user2']);
$user3 = htmlentities($_POST['user3']);

I've tried this:

while ($i <= $useramm) {
    ${"user$i"} = htmlentities($_POST['user-' + $i]);
    $i=$i+1;
}

but it shows me these errors:

Warning: A non-numeric value encountered in C:\xampp\htdocs\test.php on line 14 Notice: Undefined offset: 1 in C:\xampp\htdocs\test.php on line 14

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanfei8897 duanfei8897 2年前

    Yes, you could do this with variable variables, but you need to use concatenation operator instead of addition.

    $i = 0;
    while (++$i <= $useramm) {
        ${"user$i"} = htmlentities($_POST['user' . $i]);
    }
    

    A better way would be to use an array. Instead of numbering your field user1, user2 and so on, just use array.

    In your HTML define POST fields as the same name with [] at the end. PHP will parse this as an array with key user:

    <form method="POST">
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="submit" value="submit">
    </form>
    

    Then in PHP you can just use the array values, either in a loop or directly accesing through an index.

    foreach ($_POST['user'] as $singleUser) {
        // use $singleUser here
    }
    // or 
    $_POST['user'][0]; // first user field
    $_POST['user'][1]; // second user field
    
    点赞 评论 复制链接分享