PHP: array_merge - Manual
(PHP 4, PHP 5, PHP 7, PHP 8)
array_merge — Fusiona varios arrays en uno solo
Descripción
Si los arrays de entrada tienen claves comunes, entonces, el valor final para esa clave sobrescribirá al anterior. Sin embargo, si los arrays contienen claves numéricas, el valor final no sobrescribirá el valor original, sino que será añadido.
Las claves numéricas de los arrays de entrada serán renumeradas en claves incrementadas partiendo de cero en el array fusionado.
Parámetros
arrays-
Lista de arrays variable para fusionar.
Valores devueltos
Devuelve el array resultante. Si se invoca sin argumentos, devuelve un array vacío.
Historial de cambios
| Versión | Descripción |
|---|---|
| 7.4.0 | Esta función puede ser ahora llamada sin parámetros. Anteriormente, al menos un parámetro era requerido. |
Ejemplos
Ejemplo #1 Ejemplo con array_merge()
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
El ejemplo anterior mostrará:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
Ejemplo #2 Ejemplo simple con array_merge()
<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
print_r($result);
?>
No se olvide de que los índices numéricos serán reindexados.
Si se desea añadir elementos del segundo array al primero
sin sobrescribir o reindexar los elementos del primero,
utilice el operador de unión +:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
Las claves del primer array son preservadas. Si una clave existe en los 2 arrays, entonces el elemento del primero será utilizado y la clave correspondiente del segundo será ignorada.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
Ejemplo #3 Ejemplo con array_merge() con tipos no-array
<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array) $beginning, (array) $end);
print_r($result);
?>
El ejemplo anterior mostrará:
Array
(
[0] => foo
[1] => bar
)
Ver también
- array_merge_recursive() - Combina uno o varios arrays juntos, de manera recursiva
- array_replace() - Sustituye los elementos de un array por los de otros arrays
- array_combine() - Crea un array a partir de dos otros arrays
- los operadores de array
Found A Problem?
16 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.
--Julian4 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_merge4 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.6 years ago