How can one ensure that the entire JSON object is preserved when modifying a value in PHP?

When modifying a value in a JSON object in PHP, it's important to ensure that the entire JSON object is preserved. One way to achieve this is by decoding the JSON string into an associative array, making the necessary modifications to the array, and then encoding the array back into a JSON string.

// Sample JSON object
$jsonObject = '{"key1": "value1", "key2": "value2"}';

// Decode JSON string into an associative array
$array = json_decode($jsonObject, true);

// Modify a value in the array
$array['key1'] = 'new value';

// Encode the array back into a JSON string
$newJsonObject = json_encode($array);

// Output the modified JSON object
echo $newJsonObject;