PHP Velho Oeste 2024

array_merge

(PHP 4, PHP 5, PHP 7)

array_merge하나 이상의 배열을 병합

설명

array array_merge ( array $array1 [, array $array2 [, array $... ]] )

하나 이상의 배열의 원소들을 병합하고 앞의 배열의 끝에 배열값들을 추가한다. 그 결과 배열을 반환한다.

입력되는 배열이 같은 문자열 키를 갖는다면, 그 키에 대해서 나중에 온 값이 이전에 오는 키에 대한 값을 덮어쓸것이다. 하지만, 그 배열이 숫자 키를 포함하면, 나중 값은 원래 값을 덮어쓰지 않고, 뒤에 추가될것이다.

하나의 배열만 주어지고, 그 배열이 숫자 인덱스로 되어 있으면, 키를 연속적으로 재인덱스합니다.

인수

array1

병합할 초기 배열.

array

재귀 병합할 배열 목록 변수.

반환값

결과 배열을 반환합니다.

예제

Example #1 array_merge() 예제

<?php
$array1 
= array("color" => "red"24);
$array2 = array("a""b""color" => "green""shape" => "trapezoid"4);
$result array_merge($array1$array2);
print_r($result);
?>

위 예제의 출력:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 간단한 array_merge() 예제

<?php
$array1 
= array();
$array2 = array(=> "data");
$result array_merge($array1$array2);
?>

숫자 키는 다른 숫자로 재부여된다는것을 잊지 말것!

Array
(
    [0] => data
)

배열을 온전히 보존하기를 원하고 그들 배열에 서로를 추가하고자 한다면(이전 키를 덮어쓰지 않음), + 연산자를 사용한다:

<?php
$array1 
= array();
$array2 = array(=> "data");
$result $array1 $array2;
?>

숫자 키는 보존될것이고 따라서 그 조합이 남겨진다.

Array
(
    [1] => data
)

Warning

array_merge()의 동작은 PHP 5에서 바뀌었습니다. PHP 4와는 달리, array_merge()array형 변수만 받습니다. 그러나, 자료형 변환으로 다른 자료형을 사용할 수 있습니다. 아래 예제를 참고하십시오.

Example #3 array_merge() PHP 5 예제

<?php
$beginning 
'foo';
$end = array(=> 'bar');
$result array_merge((array)$beginning, (array)$end);
print_r($result);
?>

위 예제의 출력:

Array
(
    [0] => foo
    [1] => bar
)

참고

add a note add a note

User Contributed Notes 5 notes

up
304
Julian Egelstaff
14 years ago
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1
[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
up
37
ChrisM
2 years ago
I wished to point out that while other comments state that the spread operator should be faster than array_merge, I have actually found the opposite to be true for normal arrays. This is the case in both PHP 7.4 as well as PHP 8.0. The difference should be negligible for most applications, but I wanted to point this out for accuracy.

Below is the code used to test, along with the results:

<?php
$before
= microtime(true);

for (
$i=0 ; $i<10000000 ; $i++) {
   
$array1 = ['apple','orange','banana'];
   
$array2 = ['carrot','lettuce','broccoli'];
   
   
$array1 = [...$array1,...$array2];
}

$after = microtime(true);
echo (
$after-$before) . " sec for spread\n";

$before = microtime(true);

for (
$i=0 ; $i<10000000 ; $i++) {
   
$array1 = ['apple','orange','banana'];
   
$array2 = ['carrot','lettuce','broccoli'];
   
   
$array1 = array_merge($array1,$array2);
}

$after = microtime(true);
echo (
$after-$before) . " sec for array_merge\n";
?>

PHP 7.4:
1.2135608196259 sec for spread
1.1402177810669 sec for array_merge

PHP 8.0:
1.1952061653137 sec for spread
1.099925994873 sec for array_merge
up
10
Andreas Hofmann
2 years ago
In addition to the text and Julian Egelstaffs comment regarding to keep the keys preserved with the + operator:
When they say "input arrays with numeric keys will be renumbered" they MEAN it. If you think you are smart and put your numbered keys into strings, this won't help. Strings which contain an integer will also be renumbered! I fell into this trap while merging two arrays with book ISBNs as keys. So let's have this example:

<?php
    $test1
['24'] = 'Mary';
   
$test1['17'] = 'John';

   
$test2['67'] = 'Phil';
   
$test2['33'] = 'Brandon';

   
$result1 = array_merge($test1, $test2);
   
var_dump($result1);

   
$result2 = [...$test1, ...$test2];    // mentioned by fsb
   
var_dump($result2);
?>

You will get both:

array(4) {
  [0]=>
  string(4) "Mary"
  [1]=>
  string(4) "John"
  [2]=>
  string(4) "Phil"
  [3]=>
  string(7) "Brandon"
}

Use the + operator or array_replace, this will preserve - somewhat - the keys:

<?php
    $result1
= array_replace($test1, $test2);
   
var_dump($result1);

   
$result2 = $test1 + $test2;
   
var_dump($result2);
?>

You will get both:

array(4) {
  [24]=>
  string(4) "Mary"
  [17]=>
  string(4) "John"
  [67]=>
  string(4) "Phil"
  [33]=>
  string(7) "Brandon"
}

The keys will keep the same, the order will keep the same, but with a little caveat: The keys will be converted to integers.
up
13
fsb at thefsb dot org
4 years ago
We no longer need array_merge() as of PHP 7.4.

    [...$a, ...$b]

does the same as

    array_merge($a, $b)

and can be faster too.

https://wiki.php.net/rfc/spread_operator_for_array#advantages_over_array_merge
up
4
JoshE
2 years ago
Not to contradict ChrisM's test, but I ran their code example and I got very different results for PHP 8.0.

Testing PHP 8.0.14
1.4955070018768 sec for spread
4.4120140075684 sec for array_merge
To Top