Merge a PHP array without duplicates (array_merge_recursive_distinct)

Often enough in PHP, you’ll grab objects from a variety of sources and want to merge them into a single array of results. To merge without duplicates, add the following function to your codebase and make use of array_merge_recursive_distinct the same way you would array_merge_recursive:

// From: https://www.php.net/manual/en/function.array-merge-recursive.php#92195
if (! function_exists('array_merge_recursive_distinct')) {
    /**
     * @param array<int|string, mixed> $array1
     * @param array<int|string, mixed> $array2
     *
     * @return array<int|string, mixed>
     */
    function array_merge_recursive_distinct(array &$array1, array &$array2): array
    {
        $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;
    }
}

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *