Code Logo

Merge Arrays with array_merge()

Published at25 Jul 2026
PHP Collections Easy 0 views
Like0

Write a PHP function that takes two arrays and returns a single merged array using array_merge(). array_merge() appends the elements of the second array to the first, re-indexing numeric keys.

array_merge() is a PHP function that merges one or more arrays. For numeric keys, the values are appended and re-indexed. For string keys, later values overwrite earlier ones. It creates a new array without modifying the originals.

This is the standard way to combine arrays in PHP, unlike the + operator which preserves the first array's keys and discards duplicates from the second.

Time complexity is O(n + m) where n and m are the array lengths. The function creates a new array by copying elements from each input.

Example Input & Output

Example 1
Input
[1,2],[3,4]
Output
[1,2,3,4]
Explanation

Merge two simple arrays

Example 2
Input
([10],[20,30])
Output
[10,20,30]
Explanation

Different sizes

Example 3
Input
[],['a','b']
Output
['a','b']
Explanation

Empty first array

Example 4
Input
([1,2],[])
Output
[1,2]
Explanation

Empty second array

Example 5
Input
([],[],[])
Output
[]
Explanation

All empty

Algorithm Flow

Recommendation Algorithm Flow for Merge Arrays with array_merge()
Recommendation Algorithm Flow for Merge Arrays with array_merge()

Solution Approach

function solution($arr1, $arr2) {
    return array_merge($arr1, $arr2);
}

Best Answers

php - Approach 1
<?php
function solution($arr1, $arr2) {
    return array_merge($arr1, $arr2);
}