doukuang1897 2019-07-03 20:51
浏览 181
已采纳

有没有办法在循环中获取$ _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 2019-07-03 21:03
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?