2010-05-20 146 views
6

对你们来说可能是一个简单的问题。无法在Google上找到它。PHP连接变量

我想连接两个变量的名称;

$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。$但我不知道该怎么做。任何帮助?谢谢!

回答

27
+0

不错的链接! +1给你。 – FlyingCat 2010-05-20 19:05:31

+1

接受的答案,因为链接! :D – FlyingCat 2010-05-20 19:06:51

+0

OP的代码的最后两行暗示如果$ i == 0,他试图访问$ test0。在这种情况下,如果$ test未定义,那么$ test将评估为空字符串,{$ test。$ i}将评估为“0”。 – Dazarath 2010-05-20 19:08:44

1

这可能会实现:

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

我可以问哪里这是neccesary?

+0

我想环路二维arrays..its很难解释清楚,但我需要级联得到什么我需要。不过谢谢。 +1 – FlyingCat 2010-05-20 19:04:48

6

试试这个:

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

非常感谢! +1给你。 – FlyingCat 2010-05-20 19:06:01

7

我假设的变量被称为$ TEST0,$测试1,...,$ TEST5。你可以使用下面的代码:

${"test".$i} 

虽然,我可以建议你做$ test数组并使用$ i作为索引吗?使用$ i作为循环变量名称列表的索引非常奇怪。

代替

举个例子,:

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

用途:

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

我喜欢你的建议。我已经将接受的答案给了西蒙。 D: – FlyingCat 2010-05-20 19:08:35