How to Build a Recursive PHP Function for Merging Arrays Without Using Built-In Functions

The array_merge_recursive function in PHP merges two or more arrays. If the same keys exist in multiple arrays, their values are combined into sub-arrays. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_merge_recursive(...$arrays) {
    $result = []; // Initialize an empty array to store the merged values

    // Loop through each array
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (array_key_exists($key, $result)) {
                // If the key exists and both are arrays, merge them recursively
                if (is_array($result[$key]) && is_array($value)) {
                    $result[$key] = custom_array_merge_recursive($result[$key], $value);
                } else {
                    // Convert existing value to an array if it's not already
                    $result[$key] = (array) $result[$key];
                    $result[$key][] = $value;
                }
            } else {
                // Add new key-value pairs to the result
                $result[$key] = $value;
            }
        }
    }

    return $result;
}

// Example usage
$array1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20], 'c' => 3];
$array2 = ['a' => [2, 3], 'b' => ['z' => 30], 'd' => 4];

$mergedArray = custom_array_merge_recursive($array1, $array2);
print_r($mergedArray);
?>

Output:

Array
(
    [a] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [b] => Array
        (
            [x] => 10
            [y] => 20
            [z] => 30
        )
    [c] => 3
    [d] => 4
)

Explanation:

  1. Input Parameters:
    • Accepts a variable number of arrays using …$arrays.
  2. Result Initialization:
    • Start with an empty $result array.
  3. Outer Loop:
    • Iterate through each input array.
  4. Inner Loop:
    • For each key-value pair:
      • If the key already exists in $result:
        • If both values are arrays, merge them recursively.
        • Otherwise, convert the existing value to an array and append the new value.
      • If the key doesn’t exist, add the key-value pair to $result.
  5. Recursive Merge:
    • Use recursion to handle nested arrays.
  6. Return Value:
    • Return the $result array containing the merged values.

Keep Learning 🙂

Leave a Reply

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