Home > php教程 > php手册 > body text

php合并数组array_merge函数运算符加号与的区别

WBOY
Release: 2016-06-13 12:26:15
Original
965 people have browsed it

array_merge在参考手册中的说明如下:
array_merge() 将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
  两个的区别是:
  1.数组键名为数字键名时,要合并的两个数组中有同名数字KEY的时候,使用array_merge()不会覆盖掉原来的值,而使用“+”合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(注意:不是覆盖而是保留最先出现的那个值)。例子:

复制代码 代码如下:


  $array1 = array(1=>'0');
  $array2 = array(1=> "data");
  $result1 = $array2 + $array1;/*结果为$array2的值*/
  print_r($result);
$result = $array1 + $array2 ;/*结果为$array1的值*/
print_r($result);
$result3 = array_merge($array2,$array1);/*结果为$array2和$array1的值,键名被重新分配*/
print_r($result3);
$result4 = array_merge($array1,$array2);/*结果为$array1和$array2的值,键名被重新分配*/
print_r($result4);


输出结果为: 

复制代码 代码如下:


Array
(
[1] => data
)
Array
(
[1] => 0
)
Array
(
[0] => data
[1] => 0
)
Array
(
[0] => 0
[1] => data
)


  2.当相同数组键名为字符时,“+”运算符与键名为数字时一样,但array_merge()此时会覆盖掉前面相同键名的值。
  例子:
  

复制代码 代码如下:


$array1 = array('asd'=>'0');
  $array2 = array('asd' => "data");
  $result1 = $array2 + $array1;/*结果为$array2的值*/
  print_r($result);
$result = $array1 + $array2 ;/*结果为$array1的值*/
print_r($result);
$result3 = array_merge($array2,$array1);/*结果为$array1*/
print_r($result3);
$result4 = array_merge($array1,$array2);/*结果为$array2*/
print_r($result4);


输出结果为:

复制代码 代码如下:


Array
(
[asd] => data
)
Array
(
[asd] => 0
)
Array
(
[asd] => 0
)
Array
(
[asd] => data
)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!