How can developers optimize custom merge functions for multidimensional arrays in PHP to improve performance?

When working with multidimensional arrays in PHP, developers can optimize custom merge functions by using efficient looping techniques and minimizing unnecessary operations. One approach is to iterate through the arrays and merge the values directly instead of using built-in functions like array_merge_recursive, which can be slower for large arrays. Additionally, developers can consider using references or pointers to avoid unnecessary copying of array elements during the merge process.

function custom_array_merge($array1, $array2) {
    foreach ($array2 as $key => $value) {
        if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
            $array1[$key] = custom_array_merge($array1[$key], $value);
        } else {
            $array1[$key] = $value;
        }
    }
    return $array1;
}

$array1 = [
    'key1' => 'value1',
    'key2' => [
        'subkey1' => 'subvalue1'
    ]
];

$array2 = [
    'key2' => [
        'subkey2' => 'subvalue2'
    ],
    'key3' => 'value3'
];

$result = custom_array_merge($array1, $array2);

print_r($result);