How does PHP handle references when using array_replace_recursive() to merge arrays?

When using array_replace_recursive() to merge arrays in PHP, references are not preserved. This means that if the arrays being merged contain references, they will be lost in the resulting array. To solve this issue, you can create a custom function that recursively merges arrays while preserving references.

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

$array1 = ['a' => 1, 'b' => ['c' => 2]];
$array2 = ['b' => ['d' => 3]];

merge_arrays_recursive($array1, $array2);

print_r($array1);