PHP通过引用更改数组的值

时间:2017-09-07 19:41:00

标签: php

以下是示例代码:

<?php

$arr1 = [ 'foo' => 'bar', 'test' => '2' ];
$arr2 = [ 'foo' => 'bar', 'test' => '2' ];

$arr3 = [ $arr1, $arr2 ];

$randomArr = $arr3[mt_rand(0, count($arr3) -1)];

$randomArr['test'] = 3;

echo "$arr1: " . print_r($arr1, true);
echo "$arr2: " . print_r($arr2, true);

我在这里尝试做的是将$arr1['test']$arr2['test']的值随机更改为3。似乎$randomArr被值复制而不是通过引用复制。有没有办法通过引用进行复制,以便我可以更改$arr1$arr2内联?

2 个答案:

答案 0 :(得分:5)

您可以创建对其他数组的引用数组。

$arr3 = [ &$arr1, &$arr2 ];

然后直接更新其中一个数组而不创建$randomArr

$arr3[mt_rand(0, count($arr3) -1)]['test'] = 3;

答案 1 :(得分:3)

或者您也可以使用您的代码执行此操作:

<?php

$arr1 = [ 'foo' => 'bar', 'test' => '2' ];
$arr2 = [ 'foo' => 'bar', 'test' => '2' ];

$arr3 = [ &$arr1, &$arr2 ];

$randomArr = &$arr3[mt_rand(0, count($arr3) -1)];

print_r($randomArr);
$randomArr['test'] = 3;

echo "$arr1: " . print_r($arr1, true);
echo "$arr2: " . print_r($arr2, true);