array_merge和+的区别

键名是string,两者区别:

merge 如果键名为字符,且键名相同,array_merge()后面数组元素值会覆盖前面数组元素值

+ 如果键名为字符,且键名相同,数组相加会将最先出现的值作为结果

<?php
$arr1 = array('a'=>'PHP');
$arr2 = array('a'=>'PYTHON');
print_r(array_merge($arr1,$arr2)); //Array ( [a] => PYTHON ) 如果键名为字符,且键名相同,array_merge()后面数组元素值会覆盖前面数组元素值
print_r($arr1+$arr2); //Array ( [a] => PHP )如果键名为字符,且键名相同,数组相加会将最先出现的值作为结果

//再比如
$arr1 = array('a'=>'1','b'=>'2');
$arr2 = array('a'=>'1','b'=>'3','c'=>'2');
$ret = array_merge($arr1,$arr2);
print_r($ret);//Array ( [a] => 1 [b] => 3 [c] => 2 )
$ret = $arr1+$arr2;
print_r($ret);//Array ( [a] => 1 [b] => 2 [c] => 2 )

键名是数字,两者区别:

merge 如果键名为数字,array_merge()不会进行覆盖

+ 如果键名为数字,数组相加会将最先出现的值作为结果,后面键名相同的会被抛弃

<?php
$arr1 = array("JAVA","PHP");
$arr2 = array("PYTHON","PHP");
print_r(array_merge($arr1,$arr2));//Array ( [0] => JAVA [1] => PHP [2] => PYTHON [3] => PHP ) 如果键名为数字,array_merge()不会进行覆盖
print_r($arr1+$arr2);//Array ( [0] => JAVA [1] => PHP )如果键名为数字,数组相加会将最先出现的值作为结果,后面键名相同的会被抛弃

//再比如
$arr1 = array(1=>'1',2=>'2');
$arr2 = array(1=>'1',2=>'3',8=>'2');

$ret = array_merge($arr1,$arr2);
print_r($ret);//Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 3 [4] => 2 ) 如果数组中的键名为数字时,会格式化键名并保留所有键值。
print_r($arr1+$arr2);//Array([1] => 1[2] => 2[8] => 2)

//再比如
$arr1 = array(1,2);
$arr2 = array(1,2,8);
$ret = array_merge($arr1,$arr2);
print_r($ret);//Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 8 )
print_r($arr1+$arr2);//Array([0] => 1[1] => 2[2] => 8)
?>
posted @ 2023-12-14 10:28  朝阳1  阅读(6)  评论(0编辑  收藏  举报