How can you prevent newly non-existing keys from being added when replacing values in PHP arrays?

When replacing values in PHP arrays, care must be taken to prevent newly non-existing keys from being added unintentionally. To solve this issue, you can use the array_intersect_key function to filter out only the existing keys in the array that you want to update.

// Example array with existing keys
$array = ['key1' => 'value1', 'key2' => 'value2'];

// New values to update
$newValues = ['key1' => 'new value 1', 'key3' => 'new value 3'];

// Filter out only existing keys to prevent adding non-existing keys
$array = array_replace($array, array_intersect_key($newValues, $array));

print_r($array);