2012-12-17 20 views
2

你好我想在每次循環時給變量添加一個數字,以便我可以稍後拿起這個變量。

<?php 
$i=1; 
while($i<=5) 
    { 
    $myinfo.$i = "This is the text I can change"; 
    $i++; 
    } 
?> 

<?php echo $myinfo1 ?> 
<?php echo $myinfo2 ?> 
<?php echo $myinfo3 ?> 
<?php echo $myinfo4 ?> 
<?php echo $myinfo5 ?> 

我不能在循環中包含「myinfo1」,因爲我需要在頁面上稍微添加一點。

對不起,如果這不明確,但我不知道我想要做的正確名稱。

如果任何人都可以提供幫助,那將會很棒。

+5

arrays - use'em love'em – 2012-12-17 20:42:29

+1

不要這樣做。請。 – moonwave99

回答

4

試試這個:

<?php 
$i=1; 
while($i<=5) 
    { 
    ${'myinfo'.$i} = "This is the text I can change"; 
    $i++; 
    } 
?> 

<?php echo $myinfo1 ?> 
<?php echo $myinfo2 ?> 
<?php echo $myinfo3 ?> 
<?php echo $myinfo4 ?> 
<?php echo $myinfo5 ?> 

(但使用數組是一個更好的解決方案!)

+0

魔術就像我想要的那樣:)。非常感謝你 –

0

一個for循環將事情簡單化。

試試這個:

$myinfo1 = "String of text 1"; 
$myinfo2 = "String of text 2"; 
$myinfo3 = "String of text 3"; 
$myinfo4 = "String of text 4"; 
$myinfo5 = "String of text 5"; 

for ($i=1; $i <= 5; $i++){ 
    echo $myinfo . $i "<br>"; 
} 
0

只是爲了讓你知道這

<?php echo $myinfo1 ;?> 
         ^-------------- you are missing this 

這應該是你的代碼一樣,

<?php 
$myinfo1 = "This is the text I can change"; 
$myinfo2 = "This is the text I can change"; 
$myinfo3 = "This is the text I can change"; 
$myinfo4 = "This is the text I can change"; 
$myinfo5 = "This is the text I can change";   

for ($i = 1; $i <= 5; $i++) 
{ 
echo $myinfo.$i ; 

} 
?> 
2

你有沒有考慮使用一個數組,而不是命名變量?通過更改爲這種架構,您可以添加更多項目而無需更改代碼(添加更多行$myInfoX)。在您開發的時候,這種方法比您當前的代碼更容易閱讀和添加。

例如,

$myInfo = array(); 

    for ($i=0; $i<=5; $i++) 
    { 
    $myInfo[] = "This is the text I can change"; 
    } 

這將導致一個編號的索引的數組,你可以回想起這樣的:

<?php echo $myInfo[2]; //returns "This is the text I can change" ?> 

您也可以使用數組在這樣的循環:

<?php 
    for($info in $myInfo) 
    { 
     echo $info; 
    } 
?> 

這將依次打印數組中的每個元素。