PHP Conference Kansai 2025

array_merge_recursive

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

array_merge_recursive一つ以上の配列を再帰的にマージする

説明

array_merge_recursive(array ...$arrays): array

array_merge_recursive() は、 一つ以上の配列の要素をマージし、 前の配列の最後にもう一つの配列の値を追加します。 マージした後の配列を返します。

入力配列が同じ文字列のキーを有している場合、 マージした後の配列ではこれらのキーの値がひとつにまとめられます。 この処理は再帰的に行われます。 このため、値の一つが配列自体を指している場合、 この関数は別の配列の対応するエントリもマージします。 しかし、配列が同じ数値キーを有している場合、 後の値は元の値を上書せず、追加されます。

パラメータ

arrays

再帰的にマージしていく配列の可変リスト。

戻り値

すべての引数の配列をマージした結果の配列を返します。 引数なしで呼び出された場合、空の配列を返します。

変更履歴

バージョン 説明
7.4.0 この関数は、引数なしでも呼び出せるようになりました。 このバージョンより前では、少なくともひとつの引数が必須でした。

例1 array_merge_recursive() の例

<?php
$ar1
= array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

上の例の出力は以下となります。

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

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

参考

add a note

User Contributed Notes 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