PHP

Dynamically Merge Multiple PHP Arrays

See how to combine an arbitrary number of PHP arrays into a single array using `array_merge()` along with the spread operator or `call_user_func_array` for flexibility.

<?php
$array1 = ['apple', 'banana'];
$array2 = ['cherry', 'date'];
$array3 = ['elderberry'];

// Method 1: Merging a known number of arrays
$mergedArray = array_merge($array1, $array2, $array3);
echo "Merged Array (Method 1): " . implode(", ", $mergedArray) . "
";

// Method 2: Merging an array of arrays (e.g., from a loop or dynamic source)
$listOfArrays = [
    ['grape', 'fig'],
    ['kiwi'],
    ['lemon', 'mango']
];

// Using array_merge with the spread operator (PHP 5.6+)
$dynamicMergedArray = array_merge(...$listOfArrays);
echo "Dynamic Merged Array (Spread): " . implode(", ", $dynamicMergedArray) . "
";

// Using call_user_func_array for older PHP versions or dynamic function calls
$dynamicMergedArrayLegacy = call_user_func_array('array_merge', $listOfArrays);
echo "Dynamic Merged Array (Legacy): " . implode(", ", $dynamicMergedArrayLegacy) . "
";
?>
How it works: The `array_merge()` function combines one or more arrays, appending the second array to the first, and so on. For numeric keys, values are re-indexed. For string keys, later values overwrite earlier ones. When merging a dynamic list of arrays, the spread operator (`...`) (available in PHP 5.6+) or `call_user_func_array()` for `array_merge` provides flexible ways to pass each array in the list as a separate argument.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs