How to use array_merge_recursive() Function In PHP
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
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 )
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