PHP合并数组+号和array_merge的区别

这篇文章主要介绍了PHP合并数组+号和array_merge的区别,PHP的数组融合一般有两种做法,一种是直接使用加号相加,另一种则是使用array_merge函数进行相加,两者之间有点区别,需要的朋友可以参考下。

PHP的数组融合一般有两种做法,一种是直接使用加号相加,另一种则是使用array_merge函数进行相加,两者之间有点区别:

1.相加会证数组中的自然index不被重置

2.相加方法中,被加的数组内的值不会被覆盖

3.merge函数中的自然index会被重置

4.merge函数,无所谓被merge和merge关系,越后面的array参数,其值,会覆盖较前面的array参数相同键的值

例子:

数组1:

  1. $arr1 = array(
  2. 10 => 'valueof10',
  3. 11 => 'valueof11',
  4. 'key1' => 'dataofkey1',
  5. 'key2' => 'dataofkey2',
  6. 'array' => array(
  7. 'key1' => 1,
  8. 'key2' => 'abc',
  9. 'key3' => array(
  10. 1, 2, 'name' => 'peter'
  11. ),
  12. ),
  13. );

数组2:

  1. $arr2 = array(
  2. 10 => 'newvalueof10',
  3. 11 => 'newvalueof11',
  4. 'key1' => 'newdataofkey1',
  5. 'key3' => 'newdataofkey3',
  6. 'array' => array(
  7. 'key1' => 2,
  8. 'key2' => 'defg',
  9. 'key3' => array(
  10. 1, 2, 'name' => 'jonathan', 'gender' => 'male'
  11. ),
  12. ),
  13. );

结果比较:

  1. array (size=6)
  2. 10 => string 'valueof10' (length=9)
  3. 11 => string 'valueof11' (length=9)
  4. 'key1' => string 'dataofkey1' (length=10)
  5. 'key2' => string 'dataofkey2' (length=10)
  6. 'array' =>
  7. array (size=3)
  8. 'key1' => int 1
  9. 'key2' => string 'abc' (length=3)
  10. 'key3' =>
  11. array (size=3)
  12. 0 => int 1
  13. 1 => int 2
  14. 'name' => string 'peter' (length=5)
  15. 'key3' => string 'newdataofkey3' (length=13)
  16. array (size=8)
  17. 0 => string 'valueof10' (length=9)
  18. 1 => string 'valueof11' (length=9)
  19. 'key1' => string 'newdataofkey1' (length=13)
  20. 'key2' => string 'dataofkey2' (length=10)
  21. 'array' =>
  22. array (size=3)
  23. 'key1' => int 2
  24. 'key2' => string 'defg' (length=4)
  25. 'key3' =>
  26. array (size=4)
  27. 0 => int 1
  28. 1 => int 2
  29. 'name' => string 'jonathan' (length=8)
  30. 'gender' => string 'male' (length=4)
  31. 2 => string 'newvalueof10' (length=12)
  32. 3 => string 'newvalueof11' (length=12)
  33. 'key3' => string 'newdataofkey3' (length=13)