2016-02-14 121 views
2

有沒有一種方法可以在PHP中根據另一個因素更改正在更改哪個變量。例如:PHP - 動態訪問變量

$str1 = "The string is 1"; 
$str2 = "The string is 2"; 
$str3 = "The string is 3"; 
$X = 3; 
echo $strX; 

>> "The string is 3." 

編輯:感謝這正是我需要的:)

+2

[變量變量](http://php.net/manual/en/language.variables.variable.php):'echo $ {「str」。$ X};' –

回答

5
<?php 
$str1 = "The string is 1"; 
$str2 = "The string is 2"; 
$str3 = "The string is 3"; 
$X = 3; 
echo ${"str".$X}; 
?> 

在這裏閱讀更多Variable variables

+0

小解釋有助於未來遊客。 – devpro

3

我認爲你正在尋找

$str1 = "The string is 1"; 
    $str2 = "The string is 2"; 
    $str3 = "The string is 3"; 
    $X = "str2"; 
    echo ${$X}; 

你也可以使用

$str1 = "The string is 1"; 
    $str2 = "The string is 2"; 
    $str3 = "The string is 3"; 
    $X = "2"; 
    echo ${"str".$X};