32

I have an Entity Order which hold Suppliers in an Arraycollection. In my controller i want to check if this arraycollection is empty:

$suppliers = $order->getSuppliers();

I tried:

if(!($suppliers)) {}
if(empty($suppliers)) {}

Any ideas?

A.L
  • 10,259
  • 10
  • 67
  • 98
ChrisS
  • 736
  • 2
  • 8
  • 21

2 Answers2

94

Doctrine ArrayCollection has a method isEmpty that will do what you are looking for.

if ($suppliers->isEmpty()) { }

Take a look at the documentation for it here

Community
  • 1
  • 1
Ken Hannel
  • 2,718
  • 17
  • 20
  • Note: This is preferable over count() == 0. http://www.doctrine-project.org/api/common/2.3/source-class-Doctrine.Common.Collections.ArrayCollection.html#343-353 – Stillmatic1985 Jun 23 '17 at 12:21
  • Yes, and you are bond to Doctrine (for ever) :-/ – Uros Majeric Jun 14 '18 at 10:26
  • 1
    @UrosMajeric - not really, you would just need to ensure that your concrete methods (or your own interface) matched the Collection interface if you migrated away from Doctrine. – Ken Hannel Jul 23 '18 at 21:30
  • 4
    In addition to what @KenHannel said, one could also add `Order::hasSuppliers(): bool` method, which returns `$this->suppliers->isEmpty()`. This way, if someday you decide to migrate from Doctrine, you will need to change your code in only one place. – iloo Sep 24 '18 at 10:11
7

You can also use the count() PHP function:

if (count($suppliers) < 1) { }
A.L
  • 10,259
  • 10
  • 67
  • 98