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

图片转代码服务由CSDN问答提供 功能建议

有没有办法制作一个循环来给我这个,这取决于我想要抓取的用户数量 ?

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

我试过这个:

  while(  $ i&lt; = $ useramm){
 $ {“user $ i”} = htmlentities($ _ POST ['user-'+ $ i]); 
 $ i = $ i + 1; 
} 
    
 
 

但它显示了以下错误:

警告:在C:\中遇到非数字值 第14行的xampp \ htdocs \ test.php 注意:未定义的偏移量:第14行的C:\ xampp \ htdocs \ test.php中的1

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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
    
    打赏 评论