7

In code review I saw a developer using count($paragraph->field_events) to get the number of referenced entities.

I thought, surely that can't work, that can't be right. So the question is, what is the correct way to get the number of items from a field on an entity?

1 Answer 1

11

Using count() on a field is acceptable because there is an implementation of Countable::count in the ListInterface implemented by ItemList class where it overloads the count method to count the items, from which FieldItemList and EntityReferenceFieldItemList inherit.

So you can use:

$paragraph->field_events->count()

or

count($paragraph->field_events)

synonymously. They do the same thing.

From ItemList.php:

public function count() {
  return count($this->list);
}

If you'd like test this, you can play with this simple class. If you remove the "Implements Countable" calling count(a) on object a doesn't return the count() method, but if you add it back, it does. So on a low level, Drupal is using this so you can call count() on fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.