首页 > 文章列表 > PHP中如何通过数组变量名称输出变量的值?

PHP中如何通过数组变量名称输出变量的值?

492 2025-03-10

PHP中如何通过数组变量名称输出变量的值?

php 实现输出数组变量

在 php 中,如果要通过数组中的变量名称输出变量的值,可以使用以下几种方法:

方法 1:使用 gettype() 函数

$html['result'] = '1111111111';
$arr = [
    'urls' => "html['result']"
];
$temp = $arr['urls'];
$urls = $html['result'];
echo $$temp; // 输出 "1111111111"

方法 2:使用 eval() 函数

$html['result'] = '1111111111';
$arr = [
    'urls' => "$html['result']"
];
$temp = $arr['urls'];

eval("$temp = $temp;");

echo $temp; // 输出结果:"1111111111"

方法 3:使用 反射类**

$html['result'] = '1111111111';
$arr = [
    'urls' => 'html'
];
$temp = null;

// 使用反射获取数组的值
$reflection = new reflectionclass($arr['urls']);
$property = $reflection->getproperty('result');
$temp = $property->getvalue($html);

echo $temp;

方法 4:使用 自定义函数**

$html['result'] = '1111111111';
$arr = [
    'urls' => "html['result']"
];
$temp = $arr['urls'];

function getValue($str) {
    global $html;
    preg_match("/['(.*)']/", $str, $matches);
    return $html[$matches[1]];
}

echo getValue($temp); // 输出 "1111111111"
来源:1733128275