2010-05-20 73 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