PHP连接变量

时间:2010-05-20 18:55:28

标签: php variables concatenation

对你们来说,这可能是一个简单的问题。在谷歌找不到它。

我正在尝试连接两个变量名称;

$i=0;
 for ($i=0;$i<5;$i++){
   if($array[$i]>0){

   $test.$i=//do something
   }else{
  $test.$i=//do something
  }
}

//echo $test0 gives me nothing.
//echo $test1 gives me nothing.

我知道我不能使用$ test。$ i但不知道怎么做。任何帮助?谢谢!

4 个答案:

答案 0 :(得分:28)

答案 1 :(得分:8)

我假设变量名为$ test0,$ test1,...,$ test5。您可以使用以下内容:

${"test".$i}

尽管如此,我可以建议您将$ test作为数组并使用$ i作为索引吗?使用$ i作为循环遍历变量名列表的索引是非常奇怪的。

举个例子,而不是:

$test0 = "hello";
$test1 = "world";

使用:

$test[0] = "hello";
$test[1] = "world";

答案 2 :(得分:6)

试试这个:

 for ($i=0;$i<5;$i++){
    $the_test = $test.$i;
    if($array[$i]>0){
        $$the_test=//do something
    }
    else{
        $$the_test=//do something
    }
}

答案 3 :(得分:1)

这可能有效:

$varName = $test . $i;
$$varName = ...

我可以问这有必要吗?