PHP Conference Kansai 2025

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_merge_recursiveMescla um ou mais arrays recursivamente

Descrição

array_merge_recursive(array ...$arrays): array

array_merge_recursive() mescla os elementos de um ou mais arrays de forma que os elementos de um são colocados no final do array anterior. Retorna o array resultante da fusão.

Se os arrays dados tem as mesmas chaves string, então os valores para uma chave são mesclados em um array, e isso é feito recursivamente, sendo que, se um dos valores for um array também, este função irá mesclá-lo com os valores correspondentes no array resultante também. Se, no entanto, os arrays tem as mesmas chaves numéricas, o último valor para uma chave não sobrescreverá o valor original, e sim adicionado ao array resultante.

Parâmetros

arrays

Lista variável de arrays para mesclar recursivamente.

Valor Retornado

Um array de valores resultados da mesclagem dos argumentos. Se chamada sem nenhum argumento, retorna um array vazio.

Registro de Alterações

Versão Descrição
7.4.0 Essa função agora pode ser chamada sem nenhum parâmetro. Anteriormente, pelo menos um parâmetro era necessário.

Exemplos

Exemplo #1 Exemplo de array_merge_recursive()

<?php
$ar1
= array("cor" => array ("favorita" => "vermelho"), 5);
$ar2 = array(10, "cor" => array ("favorita" => "verde", "azul"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

O exemplo acima produzirá:

Array
(
    [cor] => Array
        (
            [favorita] => Array
                (
                    [0] => vermelho
                    [1] => verde
                )

            [0] => azul
        )

    [0] => 5
    [1] => 10
)

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 1 note

up
175
gabriel dot sobrinho at gmail dot com
15 years ago
I refactored the Daniel's function and I got it:

<?php
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;

foreach (
$array2 as $key => &$value )
{
if (
is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}

return
$merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
To Top