/** * Recursively merges two associative arrays. Unlike array_merge_recursive, this function * overwrites existing scalar values and merges sub-arrays, rather than appending numeric keys. * * @param array $array1 The base array. * @param array $array2 The array to merge into the base array. * @return array The merged array. */ function array_merge_recursive_distinct(array $array1, array $array2): array { $merged = $array1; foreach ($array2 as $key => &$value) { if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { $merged[$key] = array_merge_recursive_distinct($merged[$key], $value); } else { $merged[$key] = $value; } } return $merged; } $config1 = [ 'database' => [ 'host' => 'localhost', 'port' => 3306, 'user' => 'root' ], 'settings' => [ 'debug' => true, 'locale' => 'en' ], 'features' => ['A', 'B'] ]; $config2 = [ 'database' => [ 'port' => 5432, // Overwrites port 'password' => 'secret' ], 'settings' => [ 'locale' => 'es', // Overwrites locale 'timezone' => 'UTC' ], 'new_feature' => true, 'features' => ['C'] // Overwrites 'features' completely ]; $mergedConfig = array_merge_recursive_distinct($config1, $config2); echo "Original Config 1: "; print_r($config1); echo " Original Config 2: "; print_r($config2); echo " Merged Config (distinct): "; print_r($mergedConfig);