How to read-modify-write a multivalue entity-reference field
foreach (entity-&gt;get($field) as $k =&gt; $item) {
    $target_id = $item-&gt;target_id;
    if ($target_id == $old_value-&gt;id()) {
      $changed = TRUE;
      $item-&gt;target_id = $new_value;
    }
  }

  if ($changed) {
    $entity-&gt;save();
  }


That's it. You don't need to set any values, they are objects, your loop already updates them. You also don't need to loop over it by reference.

I just simplified it a bit because you can access target_id as a property through __set() and __get(), which has the advantage that you directly get the value and don't need to call getValue() on it.

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more information for example.