我确实有变量,比如
<?php
$num1 = 'txt1';
$num2 = 'txt2';
$num3 = 'txt3';
...
我确实有一个循环
for ($i=1; $i<100; $i++){
echo 'This is textNr'.$i.':' .$num.$i ;
}
我需要产生一个类似的结果:
这是 textNr1: txt1
当然,使用这段代码我会得到类似的东西:
这是 textNr1: 'undefined'
,因为在$num.$i中没有定义$num;
所以 $num.$i 应该被解析一次并成为 $num1 然后 $num1 应该被解析第二次像:
echo 'This is textNr'.$i.':' .$num1 ;
有人知道怎么处理吗?
这个问题的专业术语是“可变变量”或“动态变量”!
最佳答案
你应该这样做:
$nums = array();
$nums[0] = 'txt1';
$nums[1] = 'txt2';
for ($i=0; $i<100; $i++){
echo 'This is textNr'.$i.':' .$nums[$i] ;
}
或者在数组中从 1 开始索引,如果你想在循环中从 1 开始,
关于php - 如何在 PHP 中解析具有动态名称的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890520/