Efficient Method to Concatenate N Arrays in PHP

Given N arrays, the task is to concatenate multiple arrays in PHP. Array concatenation is joining two or more arrays into a single array. For example, concatenating arrays [1, 2], [3, 4], and [5, 6] results in [1, 2, 3, 4, 5, 6].Choosing the right method can impact the performance and efficiency of your code, especially when dealing with large datasets. This article explores different approaches to concatenating N arrays in PHP.

These are the following approaches:

Table of Content

  • Using array_merge() Function
  • Using the Spread Operator (PHP 7.4+)
  • Using array_merge_recursive() Function

Using array_merge() Function

The array_merge() function concatenates arrays in PHP. It can accept multiple arrays as arguments and merge them into one array.

  • The concatArrs function accepts a variable number of array arguments using the spread operator (…).
  • It uses the array_merge() function to merge all the provided arrays into a single array.

Example: This example shows concatenation of N arrays using array_merge() function.

PHP
<?php

function concatArrs(...$arrs) {
    return array_merge(...$arrs);
}

// Driver code
$arr1 = [1, 2];
$arr2 = [3, 4];
$arr3 = [5, 6];
$res = concatArrs($arr1, $arr2, $arr3);
print_r($res);

?>

Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Using the Spread Operator (PHP 7.4+)

PHP 7.4 introduced the spread operator for arrays, which allows for a concise and efficient way to concatenate arrays.

  • The concatArrs function accepts a variable number of array arguments.
  • The spread operator (…) is used to merge all arrays into a single array.

Example: This example shows concatenation of N arrays using spread operator.

PHP
<?php

function concatArrs(...$arrs) {
    return [...$arrs];
}

// Driver code
$arr1 = [1, 2];
$arr2 = [3, 4];
$arr3 = [5, 6];
$res = concatArrs(...$arr1, ...$arr2, ...$arr3);
print_r($res);

?>

Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Using array_merge_recursive() Function

array_merge_recursive() function is similar to array_merge() function but can handle nested arrays by merging them recursively.

  • The concatArrs function accepts a variable number of array arguments.
  • It uses array_merge_recursive() to merge all the provided arrays into a single array. This function is useful if you are dealing with nested arrays.

Example: This example shows concatenation of N arrays using array_merge_recursive() function.

PHP
<?php

function concatArrs(...$arrs) {
    return array_merge_recursive(...$arrs);
}

// Driver code
$arr1 = [1, 2];
$arr2 = [3, 4];
$arr3 = [5, 6];
$res = concatArrs($arr1, $arr2, $arr3);
print_r($res);

?>

Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)