我有一个数组$x
,其中包含非零数量的元素。我想创建另一个等于$y
的数组($x
)。然后,我想对$y
进行一些操作,而不会对$x
进行任何更改。我可以用这种方式创建$y
:
$y = $x;
换句话说,如果我修改以上述方式创建的$y
,我是否会更改$x
的值?
答案 0 :(得分:10)
让我们试一试:
$a = array(0,1,2);
$b = $a;
$b[0] = 5;
print_r($a);
print_r($b);
给出
Array
(
[0] => 0
[1] => 1
[2] => 2
)
Array
(
[0] => 5
[1] => 1
[2] => 2
)
数组分配始终涉及值复制。使用引用运算符通过引用复制数组。
答案 1 :(得分:1)
不,副本不会更改原件。
如果你使用了对原始数组的引用,它会改变它:
$a = array(1,2,3,4,5);
$b = &$a;
$b[2] = 'AAA';
print_r($a);
答案 2 :(得分:1)
按值复制数组。有一个问题。如果元素是引用,则复制引用但引用同一对象。
<?php
class testClass {
public $p;
public function __construct( $p ) {
$this->p = $p;
}
}
// create an array of references
$x = array(
new testClass( 1 ),
new testClass( 2 )
);
//make a copy
$y = $x;
print_r( array( $x, $y ) );
/*
both arrays are the same as expected
Array
(
[0] => Array
(
[0] => testClass Object
(
[p] => 1
)
[1] => testClass Object
(
[p] => 2
)
)
[1] => Array
(
[0] => testClass Object
(
[p] => 1
)
[1] => testClass Object
(
[p] => 2
)
)
)
*/
// change one array
$x[0]->p = 3;
print_r( array( $x, $y ) );
/*
the arrays are still the same! Gotcha
Array
(
[0] => Array
(
[0] => testClass Object
(
[p] => 3
)
[1] => testClass Object
(
[p] => 2
)
)
[1] => Array
(
[0] => testClass Object
(
[p] => 3
)
[1] => testClass Object
(
[p] => 2
)
)
)
*/