duangongqiong6958
duangongqiong6958
2014-05-06 10:54

在for循环中增加变量名称

已采纳

so I have a variable that I would like to set based on some submitted form data. On the form I have a set of fields that the user can increase the number of (that is, they can add more of the same type of field), and so I need to set the script that handles the submitted data to accomodate this.

So far this is what I have:

while ($i <= $totalproducts) {

       $product.$i = $_POST['product'.$i];
       $i++;

    }

$totalproducts holds the total number of fields. As an example, let's say I had 3 items, here's what I would like to get from the code:

$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];

I'm sure I'm close, just can't quite slot it together...

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

2条回答

  • doufang7385 doufang7385 7年前

    You can use variable variable:

    while ($i <= $totalproducts) {
       $variable = 'product' . $i;
    
       $$variable = $_POST['product' . $i];
       $i++;
    }
    

    But better will be use array:

    $products = array();
    while ($i <= $totalproducts) {
       $products[$i] = $_POST['product' . $i];
       $i++;
    }
    
    点赞 评论 复制链接分享
  • douyi6960 douyi6960 7年前

    You need to do it like this

    ${$product.$i} = $_POST['product'.$i];
    

    but this is bad style imo. Why don't you use an array? This is exactly what arrays are for.

    Also arrays have many advantages. Want to know how many products there are? Easy, just count(). Want to pass the products to say another function? Easy, just pass the array and not an unknown number of variables, etc.

    点赞 评论 复制链接分享

相关推荐