What functions in PHP can be used to copy specific elements from one array to another while preserving keys?

When copying specific elements from one array to another in PHP while preserving keys, you can use the array_intersect_key() function. This function compares the keys of two arrays and returns an array containing only the elements with keys that are present in both arrays. This way, you can selectively copy elements from one array to another based on their keys.

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

$keys_to_copy = ['b', 'c'];

$filtered_array = array_intersect_key($array2, array_flip($keys_to_copy));

$result_array = array_merge($array1, $filtered_array);

print_r($result_array);