2011-09-14 66 views
0

我想使用forloop創建多個變量...他們的名字是$var1$var15。我怎麼做?我在做$$var.$i但它不工作。如何命名這些php變量

for($i=1; $i <= 15; $i++){ 
    $$var.$i = 'this is the content of var'.$i; 
} 
+0

非常類似的問題:[在PHP中通過'for'打印變量](http://stackoverflow.com/q/7296381) –

回答

4

如果你想這樣做,就是這樣,你必須做的,而不是${$var . $i}。現在它被解釋爲($$var).$i

但是,這是非常糟糕的風格。相反,你應該使用數組[php docs]存儲的值:

$var = array(); 
for($i=1; $i <= 15; $i++){ 
    $var[$i] = 'This is the content of $var['.$i.'].'; 
} 

var_export($var); 
輸出:
array (
    1 => 'This is the content of $var[1].', 
    2 => 'This is the content of $var[2].', 
    3 => 'This is the content of $var[3].', 
    4 => 'This is the content of $var[4].', 
    5 => 'This is the content of $var[5].', 
    6 => 'This is the content of $var[6].', 
    7 => 'This is the content of $var[7].', 
    8 => 'This is the content of $var[8].', 
    9 => 'This is the content of $var[9].', 
    10 => 'This is the content of $var[10].', 
    11 => 'This is the content of $var[11].', 
    12 => 'This is the content of $var[12].', 
    13 => 'This is the content of $var[13].', 
    14 => 'This is the content of $var[14].', 
    15 => 'This is the content of $var[15].', 
) 

這是更有效和更安全的經常。

+1

+1:用於在提供替代方案之前實際回答問題。 –