How can PHP prevent overwriting existing items in an array when adding new items?

When adding new items to an array in PHP, we can prevent overwriting existing items by first checking if the key already exists in the array using the `array_key_exists()` function. If the key exists, we can choose to either skip adding the new item or update the existing item. This way, we can ensure that we do not accidentally overwrite any existing data in the array.

// Sample array
$myArray = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

// Check if key exists before adding new item
$newKey = 'key2';
if (!array_key_exists($newKey, $myArray)) {
    $myArray[$newKey] = 'new value';
} else {
    // Handle existing key
    // For example, update the existing value
    $myArray[$newKey] = 'updated value';
}

// Print the updated array
print_r($myArray);