PHP,如何使用字符作为变量名


PHP, how to use a character as a variable name?

大家好,

我目前正试图弄清楚如何使用存储在变量内的字符按名称调用另一个变量。例如:

$string = "ABCD";
$A = 10;
echo //Here I want to get $string[0]'s value, which will be A, then echo the value of the variable named after $string[0]'s value, $A. So in other words the output of the echo should be 10.

如果我对这个问题还不够清楚,请告诉我。

您应该参考PHP变量。

变量变量接受变量的值,并将其作为变量的名称。

试试这些:

$string = "ABCD";
echo ${$string[0]};  // 10
echo $$string[0];    // 10

欢迎来到SO,

根据你关于的询问,如果我对这个问题不够清楚,请告诉我。,我喜欢这个,因为你是这个网站的新手。现在让我们去现场。

你有一个变量:$string = "ABCD";,还有一个是$A = 10;,或$B = 10;,等等。

你真正想知道的是如何使用$string值获得相同的值??

解决方案:
这背后的逻辑被称为变量。变量,让您使用字符串的索引。

$string = "ABCD"; // your variable
$A = 10;          // your another variable
$B = 10;          // may your another variable

现在,让$string[0],在这个变量中,我们有一个值,值是A,所以如果我们在这个值之前放一个$符号,然后会发生什么?这将创建一个新变量,如果你回显它,你将得到这个新创建的变量的值,如果该变量有一个值。

想做就做: echo ${$string[0]};//10

您可以执行$arr1 = str_split($str);以获取字符数组,然后根据该数组执行如下回显echo "$$arr1[0]"