PHP - 动态访问变量


PHP - Accessing variables dynamically

PHP中,有没有办法根据另一个因素更改正在更改的变量。例:

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

编辑:谢谢,这正是我需要的:)

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

在此处阅读更多 变量变量

我想你正在寻找

  $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};