Programmatically get all names of an entity reference field Example: I want to get all tag names that are inside field_tags of node 5.

I can get the target_id with $node->field_tags->getValue(); 



But the problem is, I don't know what entity the target_id value belongs to. Could be a node id, term id, user id. Without that info, I am not able to use the target_id to get the name of the tag. 

How can I get all the names of an entity reference field?
The easiest way to get what you want is something like this:

$names = [];
foreach ($node-&gt;field_tags as $item) {
  if ($item-&gt;entity) {
    $names[$item-&gt;entity-&gt;id()] = $item-&gt;entity-&gt;label();
  }
}


-&gt;entity is a so called computed property, it doesn't show up in getValues(). All reference fields have it.

And yes, forget about print_r() on entity or other complex objects. They contain objects that reference each other, and print_r() can't handle that. If you have an entity, always use print_r($entity-&gt;toArray()), then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see.