PHP数组的正片和援赋值

 

同样、当PHP数组变量$arr赋值给此外一个变量$one时,此时凡是拿数组变量$arr整个复制一客被$one,尽管$arr是多维数组。

例:

$arr = array(1, 2, 3, array('one', 'two'));
$one = $arr;

# 输出原数组$arr
print_r($arr);  # Array ( [0] => 1 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => two ) ) 

# 输出新数组$one
print_r($one);  # Array ( [0] => 1 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => two ) ) 


# 修改原数组$arr,并输出
$arr[0] = 4;  
$arr[3][1] = 'three';
print_r($arr);  # Array ( [0] => 4 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => three ) ) 


# 输出新数组$one
print_r($one);  # Array ( [0] => 1 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => two ) ) 

从例子可以看出,修改原数组的值并没有影响新数组

二、当PHP数组变量$arr使用引用赋值给另一个变量$one时,此时数组变量$arr 并没有 整个复制一份给$one,而是把数组的引用赋给$one,即两个变量指向同一个数组
例:

$arr = array(1, 2, 3, array('one', 'two'));
$one = &$arr;

# 输出原数组$arr
print_r($arr);  # Array ( [0] => 1 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => two ) ) 

# 输出新数组$one
print_r($one);  # Array ( [0] => 1 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => two ) ) 


# 修改原数组$arr,并输出
$arr[0] = 4;  
$arr[3][1] = 'three';
print_r($arr);  # Array ( [0] => 4 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => three ) ) 


# 输出新数组$one
print_r($one);  # Array ( [0] => 4 [1] => 2 [2] => 3 [3] => Array ( [0] => one [1] => three ) ) 

从例子可以看出,修改了原数组的值,同时新数组值也改变了。

上面的代码,是在写博客时直接写进来的,如果直接复制粘贴到sublime text3里面,执行会报错。

图片 1

困惑半龙,才意识是代码格式来空格的由。可能坐是故是博客插件直接编写的吧。在sublime
text3里面修改格式后运行正常化。

相关文章