douju2331
douju2331
2013-12-18 07:23

是否可以使用$ i在for循环中定义PHP变量?

已采纳

I am looking to do something like the following:

for ($i=0; $i<=$number_of_bundles; $i++) {

    $rug_size . $i = $_POST['Size' . $i];

}

Unfortunately this does not work since I get "undefined index" and when I try echoeing, for example, $rug_size1 is undefined.

How can something like this be done?

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

5条回答

  • doushi6932 doushi6932 8年前

    Assuming you initialize $rug_size as an array():

    $rug_size[$i] = $_POST['Size' . $i];
    

    If you really want to use different variable names (hopefully not):

    $vn = 'rug_size' . $i;
    $$vn = $_POST['Size' . $i];
    
    点赞 评论 复制链接分享
  • doumei9832 doumei9832 8年前

    do like this .

    for ($i=0; $i<=$number_of_bundles; $i++) {
    
        ${'rug_size' . $i} = $_POST['Size' . $i];
    }
    
    点赞 评论 复制链接分享
  • duanji1924 duanji1924 8年前

    schould work like this:

    for ($i=0; $i<=$number_of_bundles; $i++) {
        $varname = 'rug_size'.$i;
        $$varname = $_POST['Size'.$i];
    }
    

    http://php.net/manual/en/language.variables.variable.php

    点赞 评论 复制链接分享
  • douyuan1049 douyuan1049 8年前

    You need wrap you dynamic variable within {} (and concat string with Dot), like:

    <?php
    $i = 1;
    ${"rug_size".$i} = "Hello world!";
    echo $rug_size1;
    ?>
    

    Output:

    Hello world!
    
    点赞 评论 复制链接分享
  • doueta6642 doueta6642 8年前

    if i am not wrong than

    $_POST['Size' , $i]
    

    will be(i.e. dot instead of comma)

    $_POST['Size'. $i]
    

    another way to avoid error:use isset()

    for ($i=0; $i<=$number_of_bundles; $i++) {
    if(isset($_POST['Size' . $i]))
     {
      $rug_size . $i = $_POST['Size' . $i];
     }
    }
    
    点赞 评论 复制链接分享