dsgfdgh14569
2013-05-15 12:30 阅读 28
已采纳

在循环中更改变量名称

I have more than 50 string. I need to put those string into one array. I try to use loop to create it. however I have trouble on auto increment var's name. $string.$s($string1, $string2). It will become Undefined variable, Any way to change var's name?

$string0="ABC";
$string1="DEF";
$string2="GHI";
...


$data=array($string0, $string1, $string2...);

for($s=0; $s<50; $s++){
    $data[$s]=$string.$s;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douhai5835 douhai5835 2013-05-15 12:32

    Not

    $string.$s;
    

    But

    ${'string'.$s};
    

    Needless to say, the best solution is:

    $data = array(
        'ABC',
        'DEF',
        'GHI',
    );
    

    or

    $data = array();
    $data[] = 'ABC';
    $data[] = 'DEF';
    $data[] = 'GHI';
    

    or

    $data = array();
    $data[0] = 'ABC';
    $data[1] = 'DEF';
    $data[2] = 'GHI';
    

    You can also replace them by your editor's function.

    I'll take one example, Notepad++. (Japanese plug-in is set on, sorry)

    Let's try like this: enter image description here

    Points:

    • Search by (\$string)([0-9]+)(=)
    • Replace to \1[\2]\3
    • Mode Regex
    点赞 评论 复制链接分享
  • doushi5117 doushi5117 2013-05-15 12:32

    something like this should work I guess :

    for($s=0; $s<50; $s++)
    {
        $myvar = "string" . $s;
        $data[$s]=$$myvar;
    }
    
    点赞 评论 复制链接分享

相关推荐