更改数组副本中的值会更改原始arra中的值

时间:2014-02-18 10:13:55

标签: php arrays variables reference

我在php中遇到一些我不理解的变量问题。

这是该问题的简化代码示例。

//Create an initial array with an sub-array
$a = array();
$a['test'] = array(1,2);

//Create an reference to $a['test'] in $b
//Changing $b[0] should now change the value in $a['test'][0]
$b = &$a['test'];
$b[0] = 3;

//Create an copy of $a into $c
$c = $a;

//Change one value in $c, which is an copy of $a.
//This should NOT change the original value of $a as it is a copy.
$c['test'][1] = 5;

print_r($a);
print_r($b);
print_r($c);

这是输出:

Array
(
    [test] => Array
        (
            [0] => 3
            [1] => 5
        )

)
Array
(
    [0] => 3
    [1] => 5
)
Array
(
    [test] => Array
        (
            [0] => 3
            [1] => 5
        )

)

该脚本创建一个带有子数组的数组,并在其中放入两个值。

然后将对子数组的引用放入b中,并以这种方式更改a中的一个值。

然后我将a的副本复制成c。

然后我改变了c的一个值。

由于c是a的副本,我希望c上的更改不会影响a。但是输出说明了一个不同的故事。

有人可以解释为什么当$ c只是$ a的副本时,更改变量$ c中的值会影响$ a中的值?为什么$ a的值中有5?

3 个答案:

答案 0 :(得分:2)

您是通过引用将$b分配给$a(这是&前缀的作用)。对$b的任何更改都将有效修改$a。只需强制声明作业:

$b = $a['test'];

$c不会修改$a。这是正在发生的事情的顺序,以及数组相同的原因:

$a['test']分配了一个1,2数组 $b被指定为对$a['test']的引用,并修改其值
然后$c被分配到$a,现已由$b修改。

答案 1 :(得分:2)

我想我找到了自己问题的答案......在这个页面上:http://www.php.net/manual/en/language.references.whatdo.php

我无法理解它为什么会这样做。我明白我应该避免在将来混合引用和数组。

我参考本节:

  

但请注意,数组内部的引用是可能的   危险的。使用a执行正常(不是通过引用)赋值   右侧的参考不会将左侧变为a   引用,但数组内的引用保留在这些正常情况下   分配。这也适用于数组所在的函数调用   通过价值传递。例如:

<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b

/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>
  

换句话说,数组的引用行为定义在   逐个元素;个人的参照行为   元素与数组的引用状态分离   容器

答案 2 :(得分:0)

您使用$b = &$a['test'];因此

将参考$ a传递给$ b

更改

$b = &$a['test'];

$b = $a['test'];