Getting only TID by Entity Query I am using Drupal 8. By retrieving an entity by Entity Query I am getting an array. How can I fetch directly the TID?

Right now I am doing the following:

  public function getCommuneTidByPostalCode(int $postalCode) {
    $commune = \Drupal::entityQuery('taxonomy_term')
      -&gt;condition('field_zipcode', $postalCode)
      -&gt;condition('vid', 'commune')
      -&gt;execute();

    if (!empty($commune)) {
      return intval(key($commune));
    }
  }


Can I drop somehow this part?:

if (!empty($commune)) {
  return intval(key($commune));
}
No. An entity query always returns a list, if you want just one record, you have to get that from the array.

The intval() isn't really necessary though, Drupal/PHP doesn't care if you use the tid as string or integer. Also, it always returns an array, and key() also works on an empty array, so you can really simplify that to just return key($communie);. And I'd actually recommend to use current() or reset() because the key is the revision ID and the value the ID and while terms currently do not yet use revisions, they will likely soon support that. 

So...

$commune = \Drupal::entityQuery('taxonomy_term')
  -&gt;condition('field_zipcode', $postalCode)
  -&gt;condition('vid', 'commune')
  -&gt;execute();

return current($commune);


Is all you need.